是否可以更改Python中父进程的环境?
在 Linux 中,当我从 shell 调用 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)
任何进程都不能更改其父进程(或任何其他现有进程的环境)。
但是,您可以通过使用修改后的环境创建新的交互式 shell 来创建新环境。
您必须生成一个新的 shell 副本,该副本使用升级后的环境并有权访问现有的 stdin、stdout 和 stderr,并进行重新初始化。
您需要执行类似使用 subprocess.Popen 来运行
/bin/bash -i
的操作。因此,原始 shell 运行 Python,Python 运行新 shell。 是的,您有很多进程正在运行。 不,这还不算太糟糕,因为原始 shell 和 Python 除了等待子 shell 完成以便它们也可以干净地退出之外,实际上并没有做任何事情。
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 语句输出到您随后获取的 stdout,或者将其写入您在父级中获取的文件。
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.
使用 bash eval 语句,并让 python 脚本输出 shell 代码
child.py:parent.sh
我将
I would use the bash eval statement, and have the python script output the shell code
child.py:
parent.sh
我需要类似的东西,我最终创建了一个脚本
envtest.py
:然后在 bash 中:
这与预期相呼应:
MYVAR is SomeValue
I needed something similar, I ended up creating a script
envtest.py
with:Then in bash:
Which echos the expected:
MYVAR is SomeValue