gpt4 book ai didi

python - 从 Python 脚本中激活 virtualenv

转载 作者:行者123 更新时间:2023-12-03 08:01:10 24 4
gpt4 key购买 nike

我正在尝试使用以下 python 代码激活我的 virtualenv(已经存在):

测试.py

import os, sys
filename = "activate"
exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)
print(os.system('pwd'))

if hasattr(sys, 'real_prefix'):
print('success')
else:
print('failed')

然后我通过终端运行这个脚本:
python Test.py
然后产生此错误:
Traceback (most recent call last):
File "activate_this.py", line 3, in <module>
exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)
File "activate", line 4
deactivate () {
^
SyntaxError: invalid syntax

我可以通过执行 cd env/bin成功激活virtualenv然后 source activate
TLDR

从 python 脚本激活 virtualenv 会在激活文件中引发语法错误。

最佳答案

激活的第一行(注意 VEnv 安装在 Win 上,但这应该不是问题):

# This file must be used with "source bin/activate" *from bash* 

那,下面的行应该告诉你 activate 是 (Bourne) 外壳 文件。

[Python 3]: compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)另一方面,与 一起使用 python 源代码。

因此,为了执行文件,您需要使用其他方式,例如 [Python 3]: subprocess - Subprocess management .你可以查看我是如何使用它的: [SO]: How to effectively convert a POSIX path to Windows path with Python in Cygwin? (@CristiFati's answer) .

但是, 我真的不明白做这一切的意义 ,您可能误解了您同事的建议。
另请注意,即使您确实设法这样做,所有 环境变量只会在调用进程中设置 ,所以它几乎无法使用(好吧,除非你也从那里执行你的脚本)。

您应该采用推荐的方式( [PyPA]: Virtualenv - User Guide ),即(来自 bash ):

source /path/to/Django/ENV/bin/activate
python your_project_startup_script.py # (as I recall, it's manage.py)

关于python - 从 Python 脚本中激活 virtualenv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54420483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com