运行scrip时自动加载virtualenv

2024-05-29 11:54:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,需要来自virtualenv的依赖项。我想知道是否有什么方法可以将它添加到我的路径中并让它自动启动它是virtualenv,运行然后返回到系统的python。

我试着玩autoenv和.env,但这似乎并不能完全满足我的要求。我也考虑过改变沙邦,让它指向virtualenv的道路,但这似乎很脆弱。


Tags: 方法路径env脚本virtualenv系统指向autoenv
3条回答

从virtualenvdocumentation

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) there’s no need for activation.

因此,如果在virtualenv中调用python可执行文件,virtualenv将是“活动的”。所以可以创建这样的脚本:

#!/bin/bash

PATH_TO_MY_VENV=/opt/django/ev_scraper/venv/bin

$PATH_TO_MY_VENV/python -c 'import sys; print(sys.version_info)'
python -c 'import sys; print(sys.version_info)'

当我在我的系统上运行这个脚本时,对python的两个调用将打印您在下面看到的内容。(Python 3.2.3在我的virtualenv中,2.7.3是我的系统Python。)

sys.version_info(major=3, minor=2, micro=3, releaselevel='final', serial=0)
sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0)

因此,当您调用$PATH_TO_MY_VENV/python时,您在virtualenv中安装的任何库都将可用。对常规系统的调用python当然不会知道virtualenv中有什么。

我很惊讶还没有人提到这个,但这就是为什么在virtualenv的bin目录中有一个名为activate_this.py的文件。您可以将其传递给execfile(),以更改当前运行的解释器的模块搜索路径。

# 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))

您可以将此文件放在脚本的顶部,以强制脚本始终在该virtualenv中运行。与修改hashbang不同,可以通过执行以下操作来使用相对路径:

script_directory = os.path.dirname(os.path.abspath(__file__))
activate_this_file = os.path.join(script_directory, '../../relative/path/to/env/bin/activate_this.py')

有两种方法:

  1. 将虚拟env python的名称放入脚本的第一行。像这样

    #!/您的/virtual/env/path/bin/python

  2. 将虚拟环境目录添加到sys.path。注意,您需要导入sys库。像这样

    导入系统

    sys.path.append('/path/to/virtual/env/lib')

如果使用第二个选项,则可能需要向sys.path(site etc)添加多个路径。最好的方法是运行虚拟env python解释器并找出sys.path值。像这样:

/your/virtual/env/bin/python

Python blah blah blah

> import sys
> print sys.path
[ 'blah', 'blah' , 'blah' ]

将sys.path的值复制到上面的代码段中。

相关问题 更多 >

    热门问题