views:

432

answers:

4

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?

10x

A: 

In certain circumstances you may want to only pass down the environment variables your subprocess needs, but I think you've got the right idea in general (that's how I do it too).

Andrew Aylett
+3  A: 

you might use my_env.get("PATH", '') instead of my_env["PATH"] in case PATH somehow not defined in the original environment, but other than that it looks fine.

SilentGhost
Good point. Thanks!
Mar_Garina
A: 

The env parameter accepts a dictionary. You can simply take os.environ, add a key (your desired variable) (to a copy of the dict if you must) to that and use it as a parameter to Popen.

Noufal Ibrahim
A: 

And what if I need to run a program by it's name using subprocess.Popen command? I have modified the Path variable and can start an app from the command line by typing "wireshark". When instead of calling subprocess.Popen(["C:\Program Files\Wireshark\wireshark.exe"]) I call subprocess.Popen(["wireshark"]), the following error is thrown: WindowsError: [Error 193] %1 is not a valid Win32 application

Alex Fedulov