使用Python脚本激活virtualenv
我想从Python脚本激活virtualenv
实例。
我知道这很容易做到,但是我看过的所有示例都使用它在env中运行命令,然后关闭子进程。
我只是想激活virtualenv
并返回外壳,就像bin / activate
一样。
像这样:
$me: my-script.py -d env-name
$(env-name)me:
这可能吗?
-
如果要在
virtualenv
下运行Python子进程,可以通过使用位于virtualenv
的/ bin /
目录中的Python解释器运行脚本来实现:# 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])
但是,如果要在当前的Python解释器下而不是子进程下激活
virtualenv
,则可以使用以下activate_this.py
脚本:# 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))