set environment variable in python script

Matthias 009 picture Matthias 009 · Dec 3, 2011 · Viewed 196.5k times · Source

I have a bash script that sets an environment variable an runs a command

LD_LIBRARY_PATH=my_path
sqsub -np $1 /homedir/anotherdir/executable

Now I want to use python instead of bash, because I want to compute some of the arguments that I am passing to the command.

I have tried

putenv("LD_LIBRARY_PATH", "my_path")

and

call("export LD_LIBRARY_PATH=my_path")

followed by

call("sqsub -np " + var1 + "/homedir/anotherdir/executable")

but always the program gives up because LD_LIBRARY_PATH is not set.

How can I fix this?

Thanks for help!

(if I export LD_LIBRARY_PATH before calling the python script everything works, but I would like python to determine the path and set the environment variable to the correct value)

Answer

jfs picture jfs · Dec 3, 2011

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))