9

I have created an environment, using virtualenv, for Python 3.4.1 which I installed on /opt. The environment is on ~/py34. Every time I want to use it, I have to type:

source py34/bin/activate
python

Is there anyway to create a shortcut, so that I don't have to type these commands every time I want to use it?

hans-t
  • 1,142

2 Answers2

11

In your ~/.bashrc file, at the end of the file, you can add the source line, so that the environment variables are set up when you open a Bash terminal anywhere. Alternatively, you can have it be an alias, as @user74158 has it below in the comments.

You could also have the python in there, but note that you will be in the Python shell when you start a Bash terminal and will have to exit out every time you want to get back to Bash.

saiarcot895
  • 10,917
0

A very versatile method is the follow:

create all virtual environments in one folder and add this to your ~/.bashrc file:

# set your directory with virtual environments here
# ( created with python3 -m venv ~/python_virtual_environments/your_env_name )
PY_VENV_DIR="/home/pascal/python_virtual_environments"

activate function sources activate script

activate() { echo "activating virtual environment: "$1"" ACTIVATE_FILE="${PY_VENV_DIR}/$1/bin/activate" echo "activate file: "$ACTIVATE_FILE""

if [ -f "$ACTIVATE_FILE" ]; then
    echo "source it"
    source "$ACTIVATE_FILE"
else
    echo "file not found!"
fi

}

auto-complete by all folders present in virtual env dir

complete -W "$(ls "${PY_VENV_DIR}")" activate

This will source the appropriate activate script in the virtual env folder. In addition you can get bash autocompletion by providing the list of directories as word list to complete.

All you need is just:

  • add the code to your ~/.bashrc
  • adapt PY_VENV_DIR accordingly
  • create venv using python3 -m venv ~/python_virtual_environments/your_env_name from package python3-venv (this could be also aliased or have a shorthand function)
  • type activate your_env_name and voilĂ , it is activated
  • deactivate will deactivate it (already built-in)

For autocompletion, see also https://askubuntu.com/a/345150/1175982

karel
  • 122,292
  • 133
  • 301
  • 332