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.
# 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))
从virtualenvdocumentation:
因此,如果在virtualenv中调用python可执行文件,virtualenv将是“活动的”。所以可以创建这样的脚本:
当我在我的系统上运行这个脚本时,对python的两个调用将打印您在下面看到的内容。(Python 3.2.3在我的virtualenv中,2.7.3是我的系统Python。)
因此,当您调用
$PATH_TO_MY_VENV/python
时,您在virtualenv中安装的任何库都将可用。对常规系统的调用python
当然不会知道virtualenv中有什么。我很惊讶还没有人提到这个,但这就是为什么在virtualenv的bin目录中有一个名为
activate_this.py
的文件。您可以将其传递给execfile()
,以更改当前运行的解释器的模块搜索路径。您可以将此文件放在脚本的顶部,以强制脚本始终在该virtualenv中运行。与修改hashbang不同,可以通过执行以下操作来使用相对路径:
有两种方法:
将虚拟env python的名称放入脚本的第一行。像这样
#!/您的/virtual/env/path/bin/python
将虚拟环境目录添加到sys.path。注意,您需要导入sys库。像这样
导入系统
sys.path.append('/path/to/virtual/env/lib')
如果使用第二个选项,则可能需要向sys.path(site etc)添加多个路径。最好的方法是运行虚拟env python解释器并找出sys.path值。像这样:
将sys.path的值复制到上面的代码段中。
相关问题 更多 >
编程相关推荐