简体   繁体   English

Python2.7 subprocess32:如何在通过Popen执行的两个脚本之间共享环境?

[英]Python2.7 subprocess32: how to share environment between two scripts executed via Popen?

I have 2 scripts: 1. Config one, which modifies about 20 environment variables and runs another small script inside, and 2. The process one which uses environment variables set by script1 to do something. 我有2个脚本:1.配置一个,可修改大约20个环境变量并在其中运行另一个小脚本,以及2.该进程使用由script1设置的环境变量来执行某些操作。

I tried to execute them one by one via Python2.7 subprocess32.Popen() and pass the same env variable to both Popen. 我试图通过Python2.7 subprocess32.Popen()一个接一个地执行它们,并将相同的env变量传递给两个Popen。 No success, environments from script1 are just empty for script2 没有成功,script1的环境对于script2只是空的

import os
import subprocess32 as subprocess
my_env = os.environ
subprocess.Popen(script1, env=my_env)
subprocess.Popen(script2, env=my_env)

How I could actually share environment between 2 scripts? 我实际上如何在两个脚本之间共享环境?

When the first subprocess exits, the changes to its environment are gone. 当第一个子流程退出时,对其环境的更改将消失。 Such changes are only propagated to its own subprocess. 此类更改仅传播到其自己的子流程。 You need to do something like this: 您需要执行以下操作:

import shlex

subprocess.Popen(". {}; {}".format(shlex.quote(script1),
                                   shlex.quote(script2)), 
                 shell=True)

But as always, using shell=True can introduce security issues. 但是与往常一样,使用shell=True会带来安全问题。

I think that the problem is in my_env=my_env , second parameter need to be env . 我认为问题出在my_env=my_env ,第二个参数需要是env

my_env = os.environ
subprocess.Popen(script1, env=my_env)
my_env = os.environ
subprocess.Popen(script2, env=my_env)

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

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