python - 从正在运行的 Python3 session 中激活 virtualenv

标签 python python-3.x virtualenv

virtualenv 的文档说要从 python 内部激活环境,请使用

activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

但是 execfile 在 Python 3 中不存在。如果我尝试使用 exec(open("venv/bin/activate_this.py").read()) , 它提示

AssertionError: You must run this like execfile('path/to/activate_this.py', dict(__file__='path/to/activate_this.py'))

这是有道理的,因为 activate_this.py 引用了 __file__

如何从 python 3 中激活 virtualenv?

最佳答案

在全局变量中传递 __file__:

exec(open("venv/bin/activate_this.py").read(), {'__file__': "venv/bin/activate_this.py"})

关于python - 从正在运行的 Python3 session 中激活 virtualenv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009735/

相关文章:

Python Panda 根据多列计算出现次数

python - 如何配置 Atom 以自动完成 Django 模板

python - Pandas - 在分类数据中填充 NaN

c++ - 选择索引不连续的 Armadillo 子矩阵

python - 如何保存棋盘游戏? Python

python - 如何从 virtualenv 中删除未使用的包?

python - Pipenv 安装运行时错误 : location not created nor specified

python - 双变量 if 语句不起作用

linux - 在虚拟环境中使用输入参数执行 python

python - 如何在Python中将字符串转换为int?