How does one enter a Python virtualenv when executing a bashscript?

We have to distinguish two cases here:

  1. You want to use/call python (or python-based tools) in your bash script, but python or those tools should be taken from and run in a virtualenv
  2. You want a script that, amongst other things, lets the shell from which you call it enter the virtualenv, so that you can interactively call python (or python-based tools) inside the virtualenv

Case 1: Using a virtualenv inside a script

How does one "enter" a Python virtualenv in a bash script?

Just like on the interactive bash command line:

source /path/to/the/virtual_env/bin/activate

What is the standard approach here?

The standard approach is not to enter the virtualenv in a bash script. Instead, call python and/or the python-based commands you want to use by their full path. To make this easier and less repetitive, you can use aliases and variables.

Case 2: Activating a virtualenv in an interactive bash session by calling a script

There already is such a script. It's called activate and it's located in the bin directory of the virtualenv. You have to source it rather than calling it like a normal command. Only then will it run in the same session instead of in a subshell, and thus only then can it make modifications to the session that won't be lost due to the subshell terminating at the end of the script.

So just do:

source /path/to/the/virtual_env/bin/activate

in your interactive shell session.

But what if you want to do more than the activate script does? You can put

source /path/to/the/virtual_env/bin/activate

into a shell script. But, due to the reason mentioned above, it won't have much effect when you call your script normally. Instead, source your script to use it from an interactive session.

Thus:

Content of my_activate.sh

#!/bin/bash

# Do something
# ...

# then
source /path/to/the/virtual_env/bin/activate

# Do more stuff
# ...

and in your interactive session

source my_activate.sh

I recommend using virtualenvwrapper. It provides some useful tools for managing your virtual environments.

pip install --user virtualenvwrapper

When you create the virtual environment, you specify which version of python should be used in the environment.

mkvirtualenv  -p /usr/local/bin/python2.6  myproject.2.6
mkvirtualenv  -p /usr/local/bin/python3.3  myproject.3.3

Then, "enter" the environment with the workon command.

workon myproject.2.6