修改环境的 Python 子进程/Popen
问题描述
我相信在稍加修改的环境下运行外部命令是很常见的情况.这就是我倾向于这样做的方式:
I believe that running an external command with a slightly modified environment is a very common case. That's how I tend to do it:
import subprocess, os
my_env = os.environ
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
subprocess.Popen(my_command, env=my_env)
我有一种直觉,认为有更好的方法;看起来还好吗?
I've got a gut feeling that there's a better way; does it look alright?
解决方案
我觉得os.environ.copy()
如果你不打算修改当前的os.environ比较好进程:
I think os.environ.copy()
is better if you don't intend to modify the os.environ for the current process:
import subprocess, os
my_env = os.environ.copy()
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
subprocess.Popen(my_command, env=my_env)
相关文章