运行 没有激活 virtualenv 的脚本

Running script without virtualenv activation

运行 使用 virtualenv 解释器(没有激活 virtualenv)的脚本和 运行 在激活的 virtualenv 中有区别吗?

venv/bin/python some_script.py

source venv/bin/activate
python some_script.py

是的。 Virtualenv 自己创建了一个解释器。就这样做,

which python

对于每个口译员,virtualenv 和您的普通口译员,看看会发生什么。他们将向您显示两个不同的 python 解释器链接。这是我的例子:

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

运行 source bin/activate 会将 PATH 变量设置为指向您的环境 bin 目录,如果您安装了其他命令行 scripts/binaries(这可能会发生)使用某些添加 shell 命令的 python 软件包),它也会 unset/set PYTHONHOME。

所以,如果 bin/python 对你有用,那么你很好,但是如果你使用的某些包开始表现异常(或者导入了错误的包),这可能是因为 Python获取错误的 PYTHONHOME 或者因为在 PATH 中找不到某个脚本。

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.

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