Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate a virtualenv with a Python script

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

like image 458
h3. Avatar asked Aug 04 '11 14:08

h3.


2 Answers

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)) 
like image 150
Lie Ryan Avatar answered Sep 17 '22 15:09

Lie Ryan


The simplest solution to run your script under virtualenv's interpreter is to replace the default shebang line with path to your virtualenv's interpreter like so at the beginning of the script:

#!/path/to/project/venv/bin/python 

Make the script executable:

chmod u+x script.py 

Run the script:

./script.py 

Voila!

like image 23
nafooesi Avatar answered Sep 16 '22 15:09

nafooesi