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

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

问题描述

在 Linux 中,当我从 shell 调用 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,假设它最初是未定义的,仍然是未定义的.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).

但是,您可以通过使用修改后的环境创建新的交互式 shell 来创建新环境.

You can, however, create a new environment by creating a new interactive shell with the modified environment.

您必须生成一个新的 shell 副本,该副本使用升级后的环境并可以访问现有的 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.

你需要做一些事情,比如使用 subprocess.Popen 来运行 /bin/bash -i.

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

所以原来的 shell 运行 Python,它运行一个新的 shell.是的,您有很多进程正在运行.不,这还不算太糟糕,因为原始 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天全站免登陆