DikobrAz
DikobrAz

Reputation: 3737

Running script without virtualenv activation

Is there a difference between running script using virtualenv interpreter (without virtualenv activation) and running it in activated virtualenv?

venv/bin/python some_script.py

vs

source venv/bin/activate
python some_script.py

Upvotes: 20

Views: 20278

Answers (3)

uak
uak

Reputation: 333

If you directly run a script or the python interpreter from the virtualenv’s bin/ directory (e.g. path/to/ENV/bin/pip or /path/to/ENV/bin/python-script.py) then sys.path will automatically be set to use the Python libraries associated with the virtualenv. But, unlike the activation scripts, the environment variables PATH and VIRTUAL_ENV will not be modified. This means that if your Python script uses e.g. subprocess to run another Python script (e.g. via a #!/usr/bin/env python shebang line) the second script may not be executed with the same Python binary as the first nor have the same libraries available to it. To avoid this happening your first script will need to modify the environment variables in the same manner as the activation scripts, before the second script is executed.

source: https://virtualenv.pypa.io/en/16.7.9/userguide.html#activate-script

Upvotes: 12

Lex Berezhny
Lex Berezhny

Reputation: 522

Running source bin/activate will set the PATH variable to point to your environment bin directory which is useful if you have other command line scripts/binaries installed (this can happen with certain python packages that add shell commands), it will also unset/set PYTHONHOME.

So, if bin/python works for you then you're fine but if some of the packages you're using start behaving strangely (or wrong one gets imported) it's probably because Python is getting the wrong PYTHONHOME or because a certain script is not found in PATH.

Upvotes: 9

Nafiul Islam
Nafiul Islam

Reputation: 82560

Yes. Virtualenv creates an interpreter in its own right. Just do this,

which python

For each interpreter, virtualenv and your normal interpreter and see what happens. They will show you two different links to python interpreter. Here's my example:

quazinafiulislam@Nafiuls-Mac: ~/Code/Python/PyTestingZone
 $ which python                                                                                               [7:49:26]
/Users/quazinafiulislam/.pyenv/shims/python

quazinafiulislam@Nafiuls-Mac: ~/Code/Python/PyTestingZone
 $ source .venv/bin/activate                                                                                  [7:49:29]
(.venv)
quazinafiulislam@Nafiuls-Mac: ~/Code/Python/PyTestingZone
 $ which python                                                                                               [7:49:35]
/Users/quazinafiulislam/Code/Python/PyTestingZone/.venv/bin/python

Upvotes: 3

Related Questions