Python:子进程中的持久shell变量
我正在尝试使用 Pythons subprocess 模块执行一系列命令,但是我需要在运行它们之前使用 export 设置 shell 变量.当然,shell 似乎不是持久的,所以当我稍后运行命令时,这些 shell 变量会丢失.
I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost.
有什么办法可以解决这个问题吗?我可以创建一个/bin/sh 进程,但是如何获得在该进程下运行的命令的退出代码?
Is there any way to go about this? I could create a /bin/sh process, but how would I get the exit codes of the commands run under that?
subprocess.Popen
接受一个可选的命名参数 env
,它是一个字典,用作子进程的环境(您所描述的外壳变量").根据需要准备一个 dict(您可以从 os.environ
的副本开始并根据需要更改它)并将其传递给所有 subprocess.Popen
调用您执行.
subprocess.Popen
takes an optional named argument env
that's a dictionary to use as the subprocess's environment (what you're describing as "shell variables"). Prepare a dict as you need it (you may start with a copy of os.environ
and alter that as you need) and pass it to all the subprocess.Popen
calls you perform.