Search code examples
pythonsubprocesssystemenvironment

Launch program in python with a different environment


I have an initial python script for which I set a specific environment (LD_LIBRARY_PATH, ...). In this script, I want to call an other program which also requires a specific environment which is not compatible with the first one. I tried os.system and subprocess commands but it looks as if, that when launching these commands, both of them keep the initial environment.

Thank you for your help.


Solution

  • subprocess.Popen() accepts an env parameter that you can use, e.g. to augment the current environment with an additional thing,

    proc = subprocess.Popen(..., env={**os.environ, 'LD_LIBRARY_PATH': '/something/'})
    

    or to wholesale replace it,

    proc = subprocess.Popen(..., env={'LD_LIBRARY_PATH': '/something/'})