Fix Python – Python subprocess/Popen with a modified environment

Question

Asked By – Oren_H

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?

Now we will see solution for issue: Python subprocess/Popen with a modified environment


Answer

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)

This question is answered By – Daniel Burke

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0