子进程运行结束后如何获取其环境变量?
我正在寻找一种方法来执行此操作,以便我可以将其传递到另一个子流程的环境。
I'm looking for a way to do this, so that I can pass it to the environment of another subprocess.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个简单的函数,它在子进程中运行命令,然后将其环境提取到当前进程中。
它基于 Fnord 的版本,没有临时文件,并带有一个标记行来区分 SET 命令和进程本身的任何输出。它不是防弹的,但它适合我的目的。
Here's a simple function which runs a command in a subprocess, then extracts its environment into the current process.
It's based on Fnord's version, without the tempfile, and with a marker line to distinguish the SET command from any output of the process itself. It's not bulletproof, but it work for my purposes.
不幸的是,孩子的环境一旦退出就会消失,即使你在 Unix 上使用 /proc 文件系统 特殊文件
/proc/[pid]/environ
它不会反映子进程所做的更改。即使上述方法确实有效,您也会遇到竞争条件:父母需要确定读取环境的“正确时间”,最好是在孩子修改环境之后立即确定。要做到这一点,父母需要与孩子协调,只要你在协调,你就可以明确地沟通。
您需要通过套接字、管道、共享内存等在父级和子级之间传递状态。 多处理模块可以使这变得更容易一些,让您可以通过队列或管道将数据从子级传递到父级。
已更新 下面是使用
multiprocessing
模块让父进程与子进程共享值以及让子进程通过队列相互通信的简要概述。它使它变得非常简单:结果:
Unfortunately the child's environment will evaporate as soon as it exits, and even if you use the /proc filesystem on Unix special file
/proc/[pid]/environ
it won't reflect changes made by the child process.Even if the above did work, you'd have a race condition: the parent would need to determine the "right time" to read the environment, ideally right after the child modified it. To do that the parent would need to coordinate with the child, and as long as you're coordinating you might as well be communicating explicitly.
You'd need to pass state between parent and child over a socket, pipe, shared memory, etc. The multiprocessing module can make this a bit easier, letting you pass data from child to parent via queues or pipes.
Updated Here's a quick sketch of using the
multiprocessing
module to let a parent process share values with child processes, and for child processes to communicate with one another across a queue. It makes it pretty simple:Result:
在 Windows 中,您可以使用 SET 命令来获取您想要的内容,如下所示:
因此,现在如果您可以使用它来读取 .bat 文件,然后根据需要使用它生成的环境变量,请修改/添加到它们,传递到新流程......等等......
In Windows you could use the SET command to get what you want, like this:
So now if you can use this to read .bat files and then use the environment variables it generates as you please, modify/add to them, pass on to a new process... etc...
你能在第一个子进程中打印它们并在 python 中处理该字符串吗?
Can you print them out in the first subprocess and deal with that string in python?
韦德的回答近乎完美。显然我的环境中有一个“'”,没有第二个元素 - 这破坏了
env[0] = env[1]
Wade's answer was nearly perfect. Apparently I had a "'" in my environment with no second element - that was breaking
env[0] = env[1]