简体   繁体   English

Python子进程:子进程完成后获取环境

[英]Python subprocess: Get environment after subprocess completed

We have a tool that comes with a shell script which sets up the environment variables necessary for running the tool.我们有一个带有 shell 脚本的工具,它设置运行该工具所需的环境变量。 It's fairly convoluted chain of different scripts that determine a bunch of stuff and export/set the env.这是相当复杂的不同脚本链,可以确定一堆东西并导出/设置 env。

We then need that environment every time we want to call the tool itself.然后,每次我们想要调用工具本身时,我们都需要该环境。

Ideally we would be able to do something like this:理想情况下,我们将能够做这样的事情:

completed_script = subprocess.run("the_settings_script.bat")
[...]
subprocess.run(["some", "other", "call"], env=completed_script.env)

That doesn't work obviously.那显然行不通。 Is there another nice way to get back the environment after running a subprocess?在运行子进程后还有另一种恢复环境的好方法吗? We could of course run the script in every subprocess.run() call before the actual tool call, but that is kind of inefficient.我们当然可以在实际工具调用之前在每个subprocess.run()调用中运行脚本,但这有点低效。

No there is no portable way.不,没有便携式方式。 In any modern OS the parent environment is passed to child processes, but in no way a child can change its parent environment.在任何现代操作系统中,父环境都传递给子进程,但子进程绝不能更改其父环境。 It used to be possible in good old MS/DOS and only with .com type programs because the address of the parent environment was stored at a well known address in the child process but I know no such tricks for Windows or any Unix-like system.它曾经在旧的 MS/DOS 中是可能的,并且只能使用 .com 类型的程序,因为父环境的地址存储在子进程中的一个众所周知的地址,但我不知道 Windows 或任何类 Unix 系统有这样的技巧.

Here the best way it to setup the environment before starting the Python interpretor.这是在启动 Python 解释器之前设置环境的最佳方式。 That way the changed environmnent will be passed to all the subprocesses.这样,更改的环境将传递给所有子流程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM