使用 Python 脚本激活 virtualenv [英] Activate a virtualenv with a Python script

查看:66
本文介绍了使用 Python 脚本激活 virtualenv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Python 脚本激活一个 virtualenv 实例.

I want to activate a virtualenv instance from a Python script.

我知道这很容易做到,但我见过的所有示例都使用它在 env 中运行命令,然后关闭子进程.

I know it's quite easy to do, but all the examples I've seen use it to run commands within the env and then close the subprocess.

我只想激活 virtualenv 并返回到 shell,就像 bin/activate 一样.

I simply want to activate the virtualenv and return to the shell, the same way that bin/activate does.

像这样:

$me: my-script.py -d env-name
$(env-name)me:

这可能吗?

相关:

virtualenv › 从脚本调用环境

推荐答案

如果你想在 virtualenv 下运行 Python 子进程,你可以通过使用位于 virtualenv 的/bin/目录中的 Python 解释器运行脚本来实现:

If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:

import subprocess

# 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 脚本:

However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py script:

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

这篇关于使用 Python 脚本激活 virtualenv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆