76

Recently, I give a try on oh my zsh, everything looks good till I try virtualevn and virtualenvwrapper. When I activate a virtualenv (e.g test), on normal bash, I will see the virtualenv name like:

(test)abc@abc:

But when I switched to zsh, I cannot see virtualenv name. Even though, I alr add virtualenv and virtualenvwrapper in plugins of oh my zsh. I also checked the activate file of my virtualenv, it contains:

f [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then        
    _OLD_VIRTUAL_PS1="$PS1"
    if [ "x" != x ] ; then
        PS1="$PS1"
    else
        PS1="(`basename \"$VIRTUAL_ENV\"`) $PS1"
    fi
        export PS1
fi

Is it because the comparision ["x" != x] return true?

Updated: I tried to echo $PS1 in activate file, and got this:

(test) %{$fg[magenta]%}%n%{$reset_color%}%{$fg[cyan]%}@%{$reset_color%}%{$fg[yellow]%}%m%{$reset_color%}%{$fg[red]%}:%{$reset_color%}%{$fg[cyan]%}%0~%{$reset_color%}%{$fg[red]%}|%{$reset_color%}%{$fg[cyan]%}⇒%{$reset_color%}

It seems the $PS1 is correct, but when I echo $PS1 in the terminal, the (test) is gone. It seems the $PS1 is override by something else!

8
  • 4
    [ "x" != x ] always returns false; it compares literal x against itself.
    – mklement0
    Commented Aug 13, 2016 at 2:52
  • then, why the basename not prepend to $PS1?
    – OhMyGosh
    Commented Aug 13, 2016 at 2:56
  • Does the prompt start with ()? Note that you needn't \ -escape the " chars. in \"$VIRTUAL_ENV\" (though it shouldn't hurt).
    – mklement0
    Commented Aug 13, 2016 at 2:58
  • How come it works fine with bash, but fails with zsh? Is there any different on sh syntax between these two?
    – OhMyGosh
    Commented Aug 13, 2016 at 3:01
  • With the code you're showing us, I wouldn't expect there to be a difference. Can you pare it down to a MCVE (Minimal, Complete, and Verifiable Example) and include the exact symptoms?
    – mklement0
    Commented Aug 13, 2016 at 3:11

17 Answers 17

106

Do this in ~/.zshrc:

plugins=(virtualenv)

POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status virtualenv)

Caveats:

1 -- add that plugin in addition to other plugins you have.

2 -- I'm using the POWERLEVEL9K theme. Maybe you theme

5
  • 7
    This was a very succinct answer that suited my situation as I too am using the same theme. The environment will show on the right side of the screen. Commented Jan 24, 2018 at 1:31
  • 2
    Hi, it doesn't work even when I only use the virtualenv plugin.
    – Labo
    Commented Feb 26, 2019 at 17:08
  • 7
    POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status root_indicator background_jobs history time virtualenv) gave me what I was looking for. Thanks William.
    – Arun Das
    Commented Sep 26, 2019 at 12:35
  • @ArunDas comment helped me by not removing the existing data on screen.
    – jknair0
    Commented Jan 7, 2020 at 15:09
  • 1
    I'm using trapd00r theme and this method didn't work for me. Commented Jun 26, 2021 at 6:33
49

The best solution is to add the following to the end of your ~/.zshrc file:

export VIRTUAL_ENV_DISABLE_PROMPT=

This will override the value in virtualenv.plugin.zsh - no need to change that file. It must be in at end of file or after source $ZSH/oh-my-zsh.sh line

3
  • I had to use export VIRTUAL_ENV_DISABLE_PROMPT=0
    – jerpint
    Commented May 31, 2018 at 1:59
  • 3
    To be more specific, I had to place it after the source ${ZSH}/oh-my-zsh.sh line. Also setting it to any value (0 or 1) as suggested in other answers didn't work for me. I am using Urxvt and powerlevel9k.
    – patzm
    Commented Jan 9, 2019 at 15:14
  • 1
    export VIRTUAL_ENV_DISABLE_PROMPT= after the source ${ZSH}/oh-my-zsh.sh line works fine for theme amuse
    – Chris
    Commented Feb 16, 2023 at 9:12
32

My setting to display Python virtualenv name for the default (a.k.a. robbyrussell) theme is the following.

In the .zshrc file

  1. virtualenv added in plugins

  2. Add custom function:

    function virtualenv_info { 
        [ $VIRTUAL_ENV ] && echo '('`basename $VIRTUAL_ENV`') '
    }
    

Navigate to your theme

  1. My theme is the default theme for zsh:
    $ vim ~/.oh-my-zsh/themes/robbyrussell.zsh-theme
    
  2. Add this command right after existing PROMPT commands:
    PROMPT+='%{$fg[green]%}$(virtualenv_info)%{$reset_color%}%'
    

Finally

$ source ~/.zshrc

PS: You can add your name or a few space before or after the PROMPT+.

Hope that helps!

5
  • 1
    The function you create is virtualenv_info but then in the prompt it is virtualenv_prompt_info is that intended ?
    – Davos
    Commented Feb 4, 2021 at 10:56
  • 1
    @Davos No, it was a typo. Check the updated answer.
    – VisioN
    Commented Jun 9, 2021 at 10:51
  • The only answer which worked for me. I'm using trapd00r theme. +1 Commented Jun 26, 2021 at 6:47
  • Wow thank you. That was VERY helpful and fixed my issue. I made a slight modification and just modified PROMPT+= in ~/.oh-my-zsh/themes/robbyrussell.zsh-theme to simply PROMPT+='%{$fg[green]%}$(virtualenv_info)%{$reset_color%}%{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)' (I like the virtualenv to be first on the far left of the prompt)
    – digitalsy
    Commented Dec 17, 2021 at 19:58
  • Works like a charm! Just leaving this updated function here for people that would like to show the actual python version used: ``` function virtualenv_info { [ $VIRTUAL_ENV ] && echo '('$VIRTUAL_ENV/bin/python --version | sed 's,Python ,,'') ' }```
    – thiezn
    Commented Apr 4, 2022 at 19:02
17

Found the problem, it's due to the theme. The theme I used in the above case is pygmalion, it won't allow u to change $PS1.

After changed to robbyrussell theme, I can change $PS1 in terminal, but still cannot see the virtualenv name. After a while debugging, I found that by default the virtualenv plugin of oh my zsh disable the prompt:

# disables prompt mangling in virtual_env/bin/activate
export VIRTUAL_ENV_DISABLE_PROMPT=1

So just comment out the line in virtualenv plugin, problem solved.

4
  • 5
    it's not working, I've commented out this, and added to the plugins, but, still not working. :(
    – ssi-anik
    Commented Oct 31, 2016 at 20:43
  • I cannot find VIRTUAL_ENV_DISABLE_PROMPT. Even by setting VIRTUAL_ENV_DISABLE_PROMPT=0 under theme robbyrussel it's not working.
    – whiletrue
    Commented Aug 30, 2018 at 14:19
  • hey, that's odd. But do you want to give a try with @Greg suggestion?
    – OhMyGosh
    Commented Sep 17, 2018 at 5:26
  • FYI, 6 years later, another solution to this is to add virtualenv to your plugins and change your theme to pygmalion-virtualenv.
    – StevieP
    Commented Aug 25, 2022 at 7:11
8

As per this guide here

  • First add virtualenv dependency under plugin in file .zshrc If this doesn't work for you, then it means that the theme(one of oh-my-zsh theme) you have selected doesn't include virtualenv name in bash prompt so try second step.

  • Go to file ~/.oh-my-zsh/themes/YOUR_THEME_NAME.zsh-theme and add this in base prompt %{$fg[green]%}$(virtualenv_prompt_info)%{$reset_color%}%

NOTE: virtualenv_prompt_info is the name of function which is declared in ~/.oh-my-zsh/plugins/virtualenv/virtualenv.plugin.zsh. If your plugin file have different function name then change it accordingly.

Or you can declare your own function in ~/.zshrc file as shown in this guide

1
  • 2
    In my case theme robbyrussell did not work. So I added this (along side others) PROMPT+=' $(virtualenv_prompt_info)' works fine now Commented Oct 21, 2019 at 21:53
5

If you are using conda to start your virtual environment the envorionment variable will be different. To figure out the name of the environment that holds your virtaulenv name type printenv and look through the output. For me it is CONDA_PROMPT_MODIFIER

after you know the name of the variable open .zshrc and add this function

function virtualenv_info { [ $CONDA_PROMPT_MODIFIER ] && echo `basename $CONDA_PROMPT_MODIFIER` }

and below that add this line

PROMPT="%{$fg[green]%}$(virtualenv_info)%{$reset_color%}%${PROMPT}"

close the editor and type source .zshrc

5

In the case you installed Anaconda using Homebrew:

brew tap homebrew/cask-versions 
brew cask install anaconda 

And you are using POWERLEVEL9K theme

git clone https://github.com/bhilburn/powerlevel9k.git ~/.oh-my-zsh/custom/themes/powerlevel9k

All you need to do is add this line to the end of .zshrc :

POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status root_indicator background_jobs history time anaconda)

There's no need for virtualenv plugin.

Edited:

In case you already had conda installed for bash and you get:

zsh: command not found: conda

Run this:

~/anaconda3/bin/conda init zsh
3

I am also using Oh My Zsh with the pygmalion theme. I had to edit the pygmalion script to add the virtual environment name before the prompt name.

  • open ~/.oh-my-zsh/themes/pygmalion.zsh-theme, modify the prompt_pygmalion_precmd function as following:
prompt_pygmalion_precmd(){
  setopt localoptions extendedglob

  local gitinfo=$(git_prompt_info)
  local gitinfo_nocolor=${gitinfo//\%\{[^\}]##\}}
  local exp_nocolor="$(print -P \"$base_prompt_nocolor$gitinfo_nocolor$post_prompt_nocolor\")"
  local prompt_length=${#exp_nocolor}
  local python_venv="($(echo $CONDA_DEFAULT_ENV)) "

  PROMPT="${python_venv}${base_prompt}${gitinfo}${post_prompt}"
}
1
2

The following steps should solve the problem:

  1. open ~/.p10k.zsh.
  2. If you use only the left prompt, make the following changes:
  typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(
    # =========================[ Line #1 ]=========================
    os_icon                    # os identifier
    dir                        # current directory
    vcs                        # git status
    # =========================[ Line #2 ]=========================
    newline                    # \n
    prompt_char                # prompt symbol
    virtualenv venv .venv env  # show the venv on the second line
  )
  1. Add the following line, preferably after you adjust POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV:
  typeset -g POWERLEVEL9K_VIRTUALENV_GENERIC_NAMES=()
  1. Save the .p10k.zsh.
  2. Restart the terminal.

Now, when you activate the virtual environment (on macOS source my_venv/bin/activate), then the name of the virtual environment (in my case, my_venv) and the version of Python installed on it (3.9.13) will appear after a beautiful Python symbol. Have a look at the attached screenshot.

1

I made it work following this link: https://askubuntu.com/a/387098

I reproduce the answer below.

How the prompt is changed is defined in the script bin/activate inside the virtual environment directory. This file is created by virtualenv from a template. Unfortunatelly, the only way of prompt modification provided by the template is prepending (env name) or whatever is set with --prompt.

To modify the prompt in the way you want, I'd suggest circumventing the setting of the prompt in bin/activate and modify the definition of PROMPT in your theme file.

First add the following to your.zsh-theme (or .zshrc)

export VIRTUAL_ENV_DISABLE_PROMPT=yes

function virtenv_indicator {
    if [[ -z $VIRTUAL_ENV ]] then
        psvar[1]=''
    else
        psvar[1]=${VIRTUAL_ENV##*/}
    fi
}

add-zsh-hook precmd virtenv_indicator

and add %(1V.(%1v).) in front of the second line of the definition of PROMPT. It should then look like this:

PROMPT='
%(1V.(%1v).)%{$fg_bold[grey]%}[%{$reset_color%}%{$fg_bold[${host_color}]%}%n@%m%{$reset_color%}%{$fg_bold[grey]%}]%{$reset_color%} %{$fg_bold[blue]%}%10c%{$reset_color%} $(git_prompt_info) $(git_remote_status)
%{$fg_bold[cyan]%}❯%{$reset_color%} '

If you want some color you could add %(1V.%{$fs_bold[yellow]%}(%1v)%{$reset_color%}.) for example.

Explanation:

virtenv_indicator will be called each time before the prompt is created. It checks if $VIRTUAL_ENV is set and not empty. If so, it sets the first element of the $psvar array to $VIRTUAL_ENV with everything before and including the last / removed (like basename $VIRTUAL_ENV but less expensive)

In the definition of PROMPT %(1V.(%1v).) checks if the first element of $psvar is set and not empty (%(1V.true-text.false-text)) and adds the content of the this element plus some parentheses ((%1v))

export VIRTUAL_ENV_DISABLE_PROMPT=yes disables any prompt setting by bin/activate scripts.

1

if you use zsh and pyenv, put this into ~/.zshrc

eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
#export PS1='($(pyenv version-name)) '$PS1

export PYENV_VIRTUALENV_DISABLE_PROMPT=1
export BASE_PROMPT=$PS1
function updatePrompt {
    if [[ "$(pyenv version-name)" != "system" ]]; then
        # the next line should be double quote; single quote would not work for me
        export PS1="($(pyenv version-name)) "$BASE_PROMPT
    else
        export PS1=$BASE_PROMPT
    fi
}
export PROMPT_COMMAND='updatePrompt'
precmd() { eval '$PROMPT_COMMAND' } # this line is necessary for zsh
1

You do not need to create new function, as per documentation - this function is created for you. https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/virtualenv

But You still need to edit theme file, as mentioned above, just enter correct function name - virtualenv_prompt_info:

PROMPT+='%{$fg[green]%}$(virtualenv_prompt_info)%{$reset_color%}%'

1
export PS1='($(pyenv version-name)) '$PS1

source & link to issue #135 in pyenv-virtualenv repo:

https://github.com/pyenv/pyenv-virtualenv/issues/135#issuecomment-582180662

0

I am using oh-my-zsh pygmalion them, and this works for me:

  • add virtualenv plugin in ~/.zshrc

  • open ~/.oh-my-zsh/themes/pygmalion.zsh-theme, modify the prompt_pygmalion_precmd function to this:

     prompt_pygmalion_precmd(){
       setopt localoptions extendedglob
    
       local gitinfo=$(git_prompt_info)
       local gitinfo_nocolor=${gitinfo//\%\{[^\}]##\}}
       local exp_nocolor="$(print -P \"$base_prompt_nocolor$gitinfo_nocolor$post_prompt_nocolor\")"
       local prompt_length=${#exp_nocolor}
       local python_venv=$(virtualenv_prompt_info)
    
       PROMPT="${python_venv}${base_prompt}${gitinfo}${post_prompt}"
     }
    

Basically just add $(virtualenv_prompt_info) to your PROMPT to wherever you prefer, here I added it to the very beginning of my PROMPT.

0

After playing with the surround answers, I found the following to be the best for my use case. This checks the $VIRTUAL_ENV_PROMPT and $VIRTUAL_ENV variables every time you change directories and sets the prompt with the correct venv info.

DEFAULT_PROMPT=$PROMPT

function cd() {
  builtin cd "$@"

  if [[ -n "$VIRTUAL_ENV_PROMPT" ]] ; then
      PROMPT="$VIRTUAL_ENV_PROMPT$DEFAULT_PROMPT"
  elif [[ -n "$VIRTUAL_ENV" ]] ; then
      PROMPT="(`basename $VIRTUAL_ENV`) $DEFAULT_PROMPT"
  else
      PROMPT=$DEFAULT_PROMPT
  fi
}
0

Back to 2023 : here something that worked for me with the theme . Search the line for "plugins" and add virtualenv (if you are using this one)

plugins=(git python brew macos colored-man-pages virtualenv vscode)

Now look for the ZSH-Theme and use

ZSH_THEME="pygmalion-virtualenv"

Reload your terminal or kill your Visual Studio code window (reloading the terminal into VS cod didn't display the change for me...)

0

For those using MacOS with oh-my-zsh and the powerlevel10k theme, to display the python version along with the activated virtual environment, I had to:

  1. Open the ~/.p10k.zsh file
  2. Search and Set in true the variable typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=true
  3. Save the file and Apply the changes with source ~/.p10k.zsh

Note: No extra plugins are needed as virtualenv is already activated by default inside the ~/.p10k.zsh file

This is how it looks:

python and venv prompts

Not the answer you're looking for? Browse other questions tagged or ask your own question.