how to customize virtualenv shell prompt

  • Last Update :
  • Techknowledgy :

See this snippet that I've used:

function virtualenv_info() {
   # Get Virtual Env
   if [
      [-n "$VIRTUAL_ENV"]
   ];
   then
   # Strip out the path and just leave the env name
   venv = "${VIRTUAL_ENV##*/}"
   else
      # In
   case you don 't have one activated
   venv = ''
   fi
      [[-n "$venv"]] && echo "(venv:$venv) "
}

# disable the
default virtualenv prompt change
export VIRTUAL_ENV_DISABLE_PROMPT = 1

VENV = "\$(virtualenv_info)";
# the '...'
are
for irrelevant info here.
export PS1 = "... ${VENV} ..."

By default, when you switch into a virtualenv with the command "workon < name_of_env >", virtualenvwrapper prepends a string along the lines of "(< name_of_env >) " to your command prompt. The problem is that I set my Bash prompt with the lines:

PROMPT_COLOR1 = '0;36m'
PROMPT_COLOR2 = '1;34m'
PS1 = '\n\[\033[$PROMPT_COLOR1\](\t)\[\033[$PROMPT_COLOR2\] \u @ \w \n\[\033[$PROMPT_COLOR1\]$ \[\033[0;39m\]'

Which yields a command prompt along the lines of:

< old_line >

   (19: 11: 05) kevin @~/research 
$

Switching into a new virtual environment with "workon < name_of_env >" turned the command prompt to something like:

< old_line >
   ( < name_of_env > )
   (19: 11: 05) kevin @~/research 
$

I simply edited the file $WORKON_HOME/postactivate to include these lines:

# color virtualenv name properly and put it after the\ n
if there is one at the start of the prompt
if [$ {
   _OLD_VIRTUAL_PS1: 0: 2
} == '\n'];
then
PS1 = "\n\[\033[$PROMPT_COLOR1\](`basename \"$VIRTUAL_ENV\"`) ${_OLD_VIRTUAL_PS1:2:${#_OLD_VIRTUAL_PS1}}"
else
   PS1 = "\[\033[$PROMPT_COLOR1\](`basename \"$VIRTUAL_ENV\"`) $_OLD_VIRTUAL_PS1 "
fi

Add to ~/.virtualenvs/postactivate the following:

PS1 = "\[\e[1;33;45m\] (`basename \"$VIRTUAL_ENV\"`) \[\e[0m\]$_OLD_VIRTUAL_PS1"

I adopted @ivanalejandro0's solution by slimming down the function a bit:

function virtualenv_info {
   # Get Virtual Env
   if [
      [-n "$VIRTUAL_ENV"]
   ];
   then
   # Strip out the path and just leave the env name
   echo "(venv:${VIRTUAL_ENV##*/})"
   fi

Or if you're feeling really hacky:

function virtualenv_info {
   [
      [-n "$VIRTUAL_ENV"]
   ] && echo "(venv:${VIRTUAL_ENV##*/})"
}

One could reduce the function in @ivanalejandro0's solution by using an "alternate value" parameter expansion. Also, as @crimson-egret commented, the call can be right in PS1 without the VENV intermediate:

function __virtualenv_ps1 {
   echo "${VIRTUAL_ENV:+(venv:${VIRTUAL_ENV##*/})}"
}

# disable the
default virtualenv prompt change
export VIRTUAL_ENV_DISABLE_PROMPT = 1

# the '...'
are
for irrelevant info here.
export PS1 = "... \$(__virtualenv_ps1) ..."

Suggestion : 2

It doesn't give any significance to conda venv. Any idea how can I do that? Edit: This should do the job:

function set_git_branch() {
   if [!-d ".git"];
   then
   BRANCH = ""
   else
      # Get the name of the branch.
   branch = $(parse_git_branch)

   # Set the final branch string.
   BRANCH = "${PURPLE}${branch}${COLOR_NONE} "
   fi
}
# Determine active Anaconda env details

function set_anacondaenv() {
   if test - z "$CONDA_PREFIX";
   then
   CONDA_VIRTUALENV = ""
   else
      conda_prefix = "$CONDA_PREFIX"
   CONDA_VIRTUALENV = " (${BLUE}${conda_prefix##*/}${COLOR_NONE})"
   fi
}

Suggestion : 3

If you want to disable the prompt for all subsequent venv activations (during your shell session), set some value to the variable checked at the condition of the block:,Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up., 1 I don't want to modify a script every time I recreate a virtual environment. There must be a simpler way. – Anthony Kong Jan 24, 2021 at 21:32 , How to replace multiple substrings from multiple lines in a file matching a pattern from a different file?

The activate script — near the bottom — keeps its old value in the _OLD_VIRTUAL_PS1 variable before prepending it with the venv's name:

if [-z "${VIRTUAL_ENV_DISABLE_PROMPT:-}"];
then
_OLD_VIRTUAL_PS1 = "${PS1:-}"
if ["x(gearshift3.8) " != x];
then
PS1 = "(gearshift3.8) ${PS1:-}"
   ...

Therefore, to immediately revert back to your old PS1, type:

export PS1 = "$_OLD_VIRTUAL_PS1"

You may edit the activate scripts and disable the above conditional block, for all future venv activations, by replacing its 1st line with this:

if false;
then

Suggestion : 4

But it uses the standard PS1 shell variable to do this. Since you’ve now used the PROMPT_COMMAND to create your prompt, PS1 is ignored, and this nice feature of virtualenv is lost.,The problem with this is that it doesn’t play well with another incredibly useful tool, virtualenv. When you activate a virtualenv, it prepends the name of the environment you are working on to the shell prompt.,For that, you’ll need to change strategies. The __git_ps1 command can be used as a single element in the expression for PS1. But it can also be used itself as the PROMPT_COMMAND env variable (this command is for bash, there’s different one for zsh). If defined, this command will be used to form PS1 dynamically.,Enter git-prompt. Again, you place this code in your home directory, and then source it from your shell startup file:

$ cd
$ curl https: //raw.github.com/git/git/v1.8.4.2/contrib/completion/git-completion.bash -o .git-completion.bash
source~/.git-completion.bash
source~/.git-prompt.sh
export PS1 = '[\u@\h \W$(__git_ps1 " (%s)")]\$ '
PROMPT_COMMAND = '__git_ps1 "" "\h:\W \u\\\$ " "[%s]\n"'
GIT_PS1_SHOWDIRTYSTATE = 1
GIT_PS1_SHOWCOLORHINTS = 1
GIT_PS1_SHOWSTASHSTATE = 1
GIT_PS1_SHOWUPSTREAM = "auto"
PROMPT_COMMAND = '__git_ps1 "" "\h:\W \u\\\$ " "[%s]\n"'

Suggestion : 5

A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps.,system_site_packages – a Boolean value indicating that the system Python site-packages should be available to the environment (defaults to False).,clear – a Boolean value which, if true, will delete the contents of any existing target directory, before creating the environment.,__VENV_NAME__ is replaced with the environment name (final path segment of environment directory).

python3 - m venv / path / to / new / virtual / environment
c: \ > c: \Python35\ python - m venv c: \path\ to\ myenv
c: \ > python - m venv c: \path\ to\ myenv
usage: venv[-h][--system - site - packages][--symlinks | --copies][--clear]
   [--upgrade][--without - pip][--prompt PROMPT][--upgrade - deps]
ENV_DIR[ENV_DIR...]

Creates virtual Python environments in one or more target directories.

positional arguments:
   ENV_DIR A directory to create the environment in .

optional arguments:
   -h, --help show this help message and exit
   --system - site - packages
Give the virtual environment access to the system
site - packages dir.
   --symlinks Try to use symlinks rather than copies, when symlinks
are not the
default
for the platform.
   --copies Try to use copies rather than symlinks, even when
symlinks are the
default
for the platform.
   --clear Delete the contents of the environment directory
if it
already exists, before environment creation.
   --upgrade Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in -place.
   --without - pip Skips installing or upgrading pip in the virtual
environment(pip is bootstrapped by
      default)
   --prompt PROMPT Provides an alternative prompt prefix
for this
environment.
   --upgrade - deps Upgrade core dependencies: pip setuptools to the
latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g.by
sourcing an activate script in its bin directory.
def create(self, env_dir):
   ""
"
Create a virtualized Python environment in a directory.
env_dir is the target directory to create an environment in .
""
"
env_dir = os.path.abspath(env_dir)
context = self.ensure_directories(env_dir)
self.create_configuration(context)
self.setup_python(context)
self.setup_scripts(context)
self.post_setup(context)

Suggestion : 6

When it is active, I mean after exec bash, if I create a virtual environment with virtualenv venv and subsequently activate it with source venv/bin/activate, (venv) should have shown up at the beginning of bash prompt. There's no way to understand that I'm running a virtual environment, although which python does in fact, show that I'm inside a virtual environment.,It can be done with the assistance of VIRTUAL_ENV variable. When a virtual environment eg. env is activated, it's path is stored in VIRTUAL_ENV and can be seen with echo $VIRTUAL_ENV.,Now format, filter and store the virtual environment name with this:,Connect and share knowledge within a single location that is structured and easy to search.

Now format, filter and store the virtual environment name with this:

local virt_env = `printf "($(echo $VIRTUAL_ENV | awk -F "/" '{print $NF}'))"`;

After that, append the virt_env variable to PS1 when required. After adding new logic the get_PS1 will look like this:

get_PS1() {
   local pwdmaxlen = 30
   local trunc_symbol = "\[$(tput setaf 1)$(tput bold)\]..."
   local virt_env = `printf "($(echo $VIRTUAL_ENV | awk -F "/" '{print $NF}'))"`;

   if [
      ["${#PWD}" - gt "$pwdmaxlen"]
   ];
   then
   local right_chunk = "\[$(tput setaf 4)$(tput bold)\]${PWD:$((${#PWD}-$pwdmaxlen)):${#PWD}}\[$(tput sgr0)\]";
   if [
      [-n "$VIRTUAL_ENV"]
   ];
   then
   PS1 = "${virt_env} ${trunc_symbol}${right_chunk} \$ ";
   else
      PS1 = "${trunc_symbol}${right_chunk} \$ ";
   fi
   else
   if [
      [-n "$VIRTUAL_ENV"]
   ];
   then
   PS1 = "${virt_env} \[$(tput setaf 4)$(tput bold)\]\$(pwd) \$\[$(tput sgr0)\] ";
   else
      PS1 = "\[$(tput setaf 4)$(tput bold)\]\$(pwd) \$\[$(tput sgr0)\] ";
   fi
   fi
}

Suggestion : 7

After you activate the environment, your command prompt will be modified to reflect the change.,virtualenv is a tool to create isolated Python environments. You can read more about it in the Virtualenv documentation. This article provides a quick summary to help you set up and use a virtual environment.,cd to your project directory and run virtualenv to create the new virtual environment.,This file can then be used by collaborators to update virtual environments using the following command.

C: \Users\ % username % \AppData\ Local\ Programs\ Python\ Python36\ python.exe
C: \Users\ % username % \AppData\ Local\ Programs\ Python\ Python36 - 32\ python.exe
pip install virtualenv
cd my - project
virtualenv--python C: \Path\ To\ Python\ python.exe venv
.\venv\ Scripts\ activate
pip freeze > requirements.txt