是否可以在Python中更改父进程的环境? [英] Is it possible to change the Environment of a parent process in Python?

查看:126
本文介绍了是否可以在Python中更改父进程的环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux中,当我从外壳中调用python时,它将复制其环境,并启动python进程.因此,如果我执行以下操作:

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"

当python进程返回时,假设FOO最初是未定义的,那么FOO仍将是未定义的. python进程(或任何子进程)是否可以修改其父进程的环境?

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.

推荐答案

没有进程可以更改其父进程(或任何其他现有进程的环境).

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.

您必须生成使用升级后的环境并可以访问现有stdin,stdout和stderr的外壳程序的新副本,并进行其重新初始化.

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.

您需要执行诸如use subprocess.Popen之类的操作来运行/bin/bash -i.

You need to do something like use subprocess.Popen to run /bin/bash -i.

因此,原始外壳运行Python,而新外壳运行.是的,您有很多正在运行的进程.不,还算不错,因为原始的shell和Python除了等待子shell完成以使它们也可以干净退出之外,实际上并没有做任何事情.

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.

这篇关于是否可以在Python中更改父进程的环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆