如何在子过程中更改ENV?

发布于 2025-01-22 06:02:46 字数 848 浏览 3 评论 0原文

我不了解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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

舂唻埖巳落 2025-01-29 06:02:46

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 of os.environ then modify it (e.g., by changing the value of PATH) to suit your needs. This is a FAQ. See, for example, this stackoverflow question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文