如何在子过程中更改ENV?
我不了解Popen子过程中ENV属性的价值。我想更改我正在运行的Python代码的虚拟环境。
示例
假设通过虚拟环境运行的名为subprocess_test.py的文件venv_main
:
# subprocess_test.py
cmd = f"C:/home/._venv/Scripts/python example.py".split()
sp = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd="/home", env = "___________")
try:
sp.wait(timeout=16)
run_output, run_error = sp.communicate()
except subprocess.TimeoutExpired:
sp.kill()
run_output, run_error = sp.communicate()
示例
import os
print(os.environ)
。 _venv/scripts 相反,它打印了subprocess_test.py执行的环境的详细信息,venv_main
也许env属性可以解决我的问题,但我不了解env属性如何工作,什么是什么环境的适当价值?
I do not understand the value of the env attribute in the Popen subprocess. I want to change the virtual environment of the python code I am running.
example
Suppose a file named subprocess_test.py which is run through virtual environment venv_main
:
# subprocess_test.py
cmd = f"C:/home/._venv/Scripts/python example.py".split()
sp = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd="/home", env = "___________")
try:
sp.wait(timeout=16)
run_output, run_error = sp.communicate()
except subprocess.TimeoutExpired:
sp.kill()
run_output, run_error = sp.communicate()
example.py
import os
print(os.environ)
It do not print the details of venv which Suprocess command takes .i.e, C:/home/._venv/Scripts
instead It print the details of environment from which subprocess_test.py executes i.e., venv_main
Maybe env attribute can solve my problem But I do not understand how env attribute work and what is the appropriate value of env?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
env
参数应为词典,其中键是env var名称。通常,您想制作os.environ
的副本,然后对其进行修改(例如,通过更改path
的值)以适合您的需求。这是一个常见问题解答。参见,例如,这个stackoverflow问题。The
env
argument should be a dictionary where the key is the env var name. In general you want to make a copy ofos.environ
then modify it (e.g., by changing the value ofPATH
) to suit your needs. This is a FAQ. See, for example, this stackoverflow question.