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)
There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using
shell=True
as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3'sshlex.quote()
to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).shell=False
is always the default where you pass an argument array.Now the safe solutions...
Method #1
Change your own process's environment - the new environment will apply to python itself and all subprocesses.
Method #2
Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.
Method #3
Unix only: Execute
env
to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.Of course if
var1
contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior withshell=True
you must compose a command array that contain the splitted string:Compact solution (provided you don't need other environment variables):
Using the env command line tool:
bash:
Similar, in Python:
You can add elements to your environment by using
and run subprocesses in a shell (that uses your
os.environ
) by using