【问题标题】:How can I activate a pyvenv vitrualenv from within python? (activate_this.py was removed?)如何从 python 中激活 pyvenv vitrualenv? (activate_this.py 被删除了?)
【发布时间】:2015-02-12 06:46:16
【问题描述】:

我正在使用 Python 3.4,并创建了一个 pyvenv,我希望从 Python 进程中激活它。使用 virtualenv,我曾经使用 activate_this.py,但在 pyvenv 中似乎没有了。

现在有没有一种简单的方法可以有效地将当前解释器更改为 virtualenv 解释器?我可能会弄乱 PATH(这是activate_this.py 所做的),但我想要一种更简单、更稳定的方式。

这是在 wsgi.py 中使用的。

【问题讨论】:

  • 是的,激活脚本取决于您的平台:docs.python.org/3/library/venv.html
  • 另外,在 Python 进程中激活并不完全有意义。您只能激活一个 virtualenv,然后使用属于该 virtualenv 的 Python 解释器。
  • 我想如果你读到这里,你会明白为什么它是有意义的:virtualenv.readthedocs.org/en/latest/… 这是我正在寻找的功能,它似乎在 pyvenv 中消失了。
  • @ChrisCooper 上面的链接已损坏。哪个版本的virtualenv?我得到了 12.1.0 和 activate_this.py 是否适合我,或者我没有从你的问题中得到正确的答案。
  • “Python 3.x 还没有被大量使用”这绝对不是真的。

标签: python-3.x mod-wsgi


【解决方案1】:

我使用了 virtualenv 本身使用的不同方法:

# the current Python interpreter is not from the virtual environment
file = __file__
if file.endswith('.pyc'):
    file = file[:-1]
venv_executable = PROJECT_DIR / 'venv' / 'bin' / 'python'
popen = subprocess.Popen([venv_executable, file] + sys.argv[1:])
raise SystemExit(popen.wait())

【讨论】:

  • 只使用sys.exit 而不是引发 SystemExit
【解决方案2】:

pyvenvvenv 模块不支持此功能。第三方virtualenvdoes support this using activate_this.py,但that feature was not included in the built-in venv module

您可以尝试从基于virtualenv 的环境中借用activate_this.py 的副本;它似乎有效,虽然我不能发誓它会是完美的(venv/pyvenv 在启动过程中使用了一些魔法;不清楚是否所有这些都通过 activate_this.py 复制)。

它的 virtualenv 文档对于 Python 3 来说已经过时了(他们声称你使用了 execfile,它并不存在)。兼容 Python 3 的替代方案是:

activator = 'some/path/to/activate_this.py'  # Looted from virtualenv; should not require modification, since it's defined relatively
with open(activator) as f:
    exec(f.read(), {'__file__': activator})

activate_this.py 所做的一切都不是神奇的,因此您可以手动执行相同的更改而无需从 virtualenv 中掠夺(调整 PATHsys.pathsys.prefix 等),但是借用可以更简单这种情况。

【讨论】:

猜你喜欢
  • 2014-09-21
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多