Python conda virtual environment in bash prompt


I was forced to use the python package manager conda for some work, as it proved to be the easiest way to install a certain python module. A nice thing about conda is the ability to set up multiple virtual environments which can each use different versions of python modules. You can set a conda virtual environment with:

conda create -n envname 

There are also lots of other options to set such as the python version (python=3.6).

Then the environment is activated with:

source activate envname

By default, conda puts the name of the virtual environment (envname) at the start of the PS1 bash prompt. For those of us with customised bash prompts, this can look really ugly. For instance, my prompt normally looks like this:

┏[02:17:31] johngodlee@Johns-MBP ~ [mac_master=] 

But with conda’s defaults it looks like this:

(lidar)┏[02:17:31] johngodlee@Johns-MBP ~ [mac_master=] 

It would be nice to put the environment name somewhere else in the prompt, which is what I set out to do. So the first things to do is to stop conda putting the env name at the start of the prompt. Edit ~/.condarc to include:

changeps1: false

Then in ~/.bash_profile (or ~/.bashrc if on Linux), add the following function above the PS1= lines:

get_conda_env ()
    if [ ! -z "$CONDA_DEFAULT_ENV" ]; then
        printf -- "%s" "($CONDA_DEFAULT_ENV)"
        printf -- "%s" ""

Then in the PS1= lines it’s simple to just call the variable created by get_conda_env():


y bash prompt definition currently looks like this:

PS1='┏'	# Elbow
PS1+='[\T]'	# Time
PS1+=' '	# Space 
PS1+='\u@\h'	# User@hostname
PS1+=' ' 	# Space
PS1+='\[\e[31m\]\w\[\e[m\]'	# current dir
PS1+=' '	# Space
PS1+='\[\e[96m\]$(__git_ps1 "[%s]")\[\e[m\]'  # git branch
PS1+=' '	# Space
PS1+='\[\e[34m\]$(get_conda_env)\[\e[m\]'  # conda env
PS1+=' '	# Space
PS1+='\n'	# New line
PS1+='┗'	# Elbow
PS1+='$'	# $
PS1+=' '	# Space

And looks like this:

┏[02:17:31] johngodlee@Johns-MBP ~ [mac_master=] (envname)