Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Shortcuts for Python 3's venv for virtualenvwrapper users.
export VENV_HOME=~/.venvs
export VENV_PYTHON=/usr/bin/python3.6
fn_workon() {
if [ -f "${VENV_HOME}/${1}/bin/activate" ]; then
export VENV_CURRENT="${VENV_HOME}/${1}"
# Run commands before activation
if [ -f "${VENV_CURRENT}/" ]; then
echo "Activating venv ${1}..."
. "${VENV_CURRENT}/bin/activate"
# Run commands after activation
if [ -f "${VENV_CURRENT}/" ]; then
echo "Could not find the venv '${1}'. Here is a list of venvs:"
alias workon=fn_workon
fn_mkvirtualenv() {
if [ -z "${VENV_HOME}" ]; then
echo "VENV_HOME is not set; we don't know where to create your venv."
echo "Creating a new venv at: ${VENV_HOME}/${1}..."
# Create the venv
${VENV_PYTHON} -m venv "${VENV_HOME}/${1}"
# Create script to run before venv activation
echo "# Commands to be run before venv activation" >> "${VENV_HOME}/${1}/"
# Create script to run after venv activation, default to current directory
echo "# Commands to be run after venv activation" >> "${VENV_HOME}/${1}/"
echo "cd ${PWD}" >> "${VENV_HOME}/${1}/"
# Activate the new venv
fn_workon "${1}"
# Get the latest pip
echo "Upgrading to latest pip..."
pip install --quiet --upgrade pip
alias mkvirtualenv=fn_mkvirtualenv
fn_rmvirtualenv() {
if [ -z "${VENV_HOME}" ]; then
echo "VENV_HOME is not set; not removing."
echo "Removing venv at: ${VENV_HOME}/${1}..."
deactivate 2>/dev/null
rm -rf "${VENV_HOME}/${1}"
alias rmvirtualenv=fn_rmvirtualenv
fn_lsvirtualenv() {
if [ -z "${VENV_HOME}" ]; then
echo "VENV_HOME is not set; can not show venvs."
ls -1 "${VENV_HOME}/"
alias lsvirtualenv=fn_lsvirtualenv
fn_cdvirtualenv() {
alias cdvirtualenv=fn_cdvirtualenv
# Tab Completions
COMPREPLY=($(compgen -W "$(ls $VENV_HOME)"))
complete -F _venv_completions workon
complete -F _venv_completions cdvirtualenv
complete -F _venv_completions rmvirtualenv

This comment has been minimized.

Copy link

vsalvino commented Jul 26, 2019

I have a similar setup for PowerShell. Works well in both Windows PowerShell, and the new cross-platform open source PowerShell Core (which I really am loving).

Put this in your profile, which you can open with: notepad $PROFILE from a powershell prompt.

function workon {
    & "$HOME\Envs\$($args[0])\Scripts\Activate.ps1"

function mkvirtualenv {
    Write-Host "Making venv at: $HOME\Envs\$($args[0])"
    & python -m venv "$HOME\Envs\$($args[0])"
    workon $args[0]

function rmvirtualenv {
    Write-Host "Deleting venv at: $HOME\Envs\$($args[0])"
    Remove-Item -Recurse $HOME\Envs\$($args[0])

function pyclean {
    # Deletes .pyc files recursively from current directory.
    Get-ChildItem -Recurse *.pyc | foreach { Write-Host $_.FullName; Remove-Item $_ }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.