Activate a virtualenv with a Python script

h3. picture h3. · Aug 4, 2011 · Viewed 96.4k times · Source

I want to activate a virtualenv instance from a Python script.

I know it's quite easy to do, but all the examples I've seen use it to run commands within the env and then close the subprocess.

I simply want to activate the virtualenv and return to the shell, the same way that bin/activate does.

Something like this:

$me: my-script.py -d env-name
$(env-name)me:

Is this possible?

Relevant:

virtualenv › Invoking an env from a script

Answer

Lie Ryan picture Lie Ryan · Feb 9, 2013

If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:

import subprocess

# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"

# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"

subprocess.Popen([python_bin, script_file])

However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py script:

# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

execfile(activate_this_file, dict(__file__=activate_this_file))