Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)
edited by

If you do not want to modify the os.environ for the current process then the os.environ.copy() is better to use below is the code for the same:-

import subprocess, os

my_env = os.environ.copy()

my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"] subprocess.Popen(my_command, env=my_env)

To know more about this you can have a look at the following video:-

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...