Skip to content

Instantly share code, notes, and snippets.

@coccoinomane
Last active November 18, 2022 15:29
Show Gist options
  • Save coccoinomane/1035e8d8b5f134930fbf9a5eac541d07 to your computer and use it in GitHub Desktop.
Save coccoinomane/1035e8d8b5f134930fbf9a5eac541d07 to your computer and use it in GitHub Desktop.
Bash / zsh function to easily create, activate and deactivate virtual environments for Python 3

Run dotvenv in an empty folder to create a virtual env from scratch and activate it immediately:

$ dotvenv
Created virtual env
Activated virtual env
(.venv) $

Run again to deactivate the virtual env:

(.venv) $ dotvenv
Deactivated virtual env
$

Run for a third time to activate again the virtual env, and so on:

$ dotvenv
Activated virtual env
(.venv) $

Custom prompt

If you provide an argument, the virtual environment will be created with a custom prompt:

$ dotvenv my-project
Created virtual env with 'my-project' prompt
Activated virtual env
(my-project) $

Run again to deactivate the virtual env:

(my-project) $ dotvenv
Deactivated virtual env
$

Running another time will reactivate the virtual env, remembering the custom prompt:

$ dotvenv
Activated virtual env
(my-project) $

Error codes

The function will return the following status codes upon encountering an error:

  • code 10 > there was a problem with the existing .venv folder
  • code 20 > there was a problem creating the .venv folder
  • code 30 > the created virtual env could not be activated
## Run dotvenv to create & activate a Python virtual environment in
## the .venv folder. Optionally provide an argument to create a custom
## prompt for the virtual environment.
##
## If the .venv folder already exists, activate / deactivate the
## existing virtual environment.
##
## Updated and documented version on Github:
## https://gist.github.com/coccoinomane/1035e8d8b5f134930fbf9a5eac541d07
dotvenv() {
# If the .venv folder already exists, just activate
# or deactivate it
if [[ -d ".venv" ]]; then
if [[ -n $VIRTUAL_ENV ]]; then
if deactivate; then
echo "Deactivated virtual env"
return 0
else
return 10
fi
else
if source .venv/bin/activate; then
echo "Activated virtual env"
return 0
else
return 10
fi
fi
fi
## Othewise, create a new virtual environment in .venv
## with the given prompt
if [[ -z $1 ]]; then
if python3 -m venv .venv; then
echo "Created virtual env"
else
return 20
fi
else
if python3 -m venv .venv --prompt "$1"; then
echo "Created virtual env with '$1' prompt"
else
return 20
fi
fi
## Activate the virtual env after creating it
if source .venv/bin/activate; then
echo "Activated virtual env"
return 0
fi
return 30
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment