是否可以改变Python中父过程的环境?
在Linux中,当我从外壳调用Python时,它复制了其环境并启动Python过程。因此,如果我做类似以下操作的事情:
import os
os.environ["FOO"] = "A_Value"
当Python进程返回时,FOO(假设最初是未定义的)仍将是未定义的。 Python流程(或任何儿童过程)是否有办法修改其父过程的环境?
我知道您通常会使用类似问题来解决此问题,
source script_name.sh
但这与我的其他要求相抵触。
In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:
import os
os.environ["FOO"] = "A_Value"
When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?
I know you typically solve this problem using something like
source script_name.sh
But this conflicts with other requirements I have.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有流程可以更改其父过程(或任何其他现有过程“环境)。
但是,您可以通过使用修改后的环境创建新的交互式外壳来创建一个新的环境。
您必须产生一个使用升级环境的外壳的新副本,并可以访问现有的stdin,stdout和stderr,并进行重新定性舞蹈。
您需要做一些事情,例如使用subprocess.popen运行
/bin/bash -i
。因此,原始的外壳运行的是Python,它运行了一个新的外壳。是的,您运行了很多过程。不,这还不错,因为原始的外壳和Python除了等待子壳完成外,还没有做任何事情,因此他们也可以干净地退出。
No process can change its parent process (or any other existing process' environment).
You can, however, create a new environment by creating a new interactive shell with the modified environment.
You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout and stderr, and does its reinitialization dance.
You need to do something like use subprocess.Popen to run
/bin/bash -i
.So the original shell runs Python, which runs a new shell. Yes, you have a lot of processes running. No it's not too bad because the original shell and Python aren't really doing anything except waiting for the subshell to finish so they can exit cleanly, also.
对于任何儿童过程,都不可能改变父程流程的环境。您能做的最好的方法是输出Shell语句,然后将其源代码源,或将其写入您在父母中的文件中。
It's not possible, for any child process, to change the environment of the parent process. The best you can do is to output shell statements to stdout that you then source, or write it to a file that you source in the parent.
python脚本输出shell code
child.py:parent.sh
我将使用bash eval语句,并让
I would use the bash eval statement, and have the python script output the shell code
child.py:
parent.sh
我需要类似的东西,最终我创建了一个脚本
envtest.py
with:in bash:
哪个回声:
myvar是somevalue
I needed something similar, I ended up creating a script
envtest.py
with:Then in bash:
Which echos the expected:
MYVAR is SomeValue