Modify environment variable for subprocess

Laura Creighton lac at
Wed Sep 23 12:37:23 CEST 2015

In a message of Wed, 23 Sep 2015 02:51:53 -0700, loial writes:
>I need to modify the LIBPATH environment variable when running a process via subprocess, but otherwise retain the existing environment.
>Whats the best way to do that?

import subprocess, os
my_env = os.environ  # if your program should be able to modify the current env
# otherwise
my_env = os.environ.copy() # if it shouldn't

# if you just want to add something to the existing LIBPATH
my_env["LIBPATH"] = "/where/I/want/to/look/first:" + my_env["LIBPATH"]
# otherwise
my_env["LIBPATH"] = "/what/I/want"

subprocess.Popen(my_program, env=my_env)

Setting os.environ leaks memory under Mac OS and FreeBSD.
I am not sure if this means that if  you do this a gazillion times
on a Mac you will have a problem.


More information about the Python-list mailing list