是否可以在 Python 中更改父进程的环境?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/263005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to change the Environment of a parent process in Python?
提问by grieve
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:
在 Linux 中当我从 shell 调用 python 时,它会复制它的环境,并启动 python 进程。因此,如果我执行以下操作:
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?
当python进程返回时,FOO,假设它最初是未定义的,仍然是未定义的。python进程(或任何子进程)有没有办法修改其父进程的环境?
I know you typically solve this problem using something like
我知道你通常使用类似的东西来解决这个问题
source script_name.sh
But this conflicts with other requirements I have.
但这与我的其他要求相冲突。
采纳答案by S.Lott
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.
但是,您可以通过使用修改后的环境创建新的交互式 shell 来创建新环境。
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.
您必须生成一个新的 shell 副本,该副本使用升级后的环境并可以访问现有的 stdin、stdout 和 stderr,并进行重新初始化。
You need to do something like use subprocess.Popen to run /bin/bash -i
.
您需要执行一些操作,例如使用 subprocess.Popen 来运行/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 运行 Python,它运行一个新的 shell。是的,您有很多进程正在运行。不,这还不错,因为原始 shell 和 Python 并没有真正做任何事情,除了等待子 shell 完成以便它们也可以干净地退出。
回答by Martin v. L?wis
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.
任何子进程都不可能改变父进程的环境。您能做的最好的事情是将 shell 语句输出到标准输出,然后您将其作为来源,或者将其写入您在父级中作为来源的文件。
回答by JimB
I would use the bash eval statement, and have the python script output the shell code
我会使用 bash eval 语句,并让 python 脚本输出 shell 代码
child.py:
孩子.py:
#!/usr/bin/env python
print 'FOO="A_Value"'
parent.sh
父文件
#!/bin/bash
eval `./child.py`