在python脚本中设置环境变量

在python脚本中设置环境变量

本文介绍了在python脚本中设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本设置一个环境变量运行一个命令

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

现在我想使用python而不是bash,因为我想计算我传递命令的一些参数。



我尝试过

  putenv(LD_LIBRARY_PATH,my_path)

  call(export LD_LIBRARY_PATH = my_path)

后跟

  call(sqsub -np+ var1 +/ homedir / anotherdir /可执行文件)

但总是程序放弃,因为LD_LIBRARY_PATH未设置。



如何解决这个问题?



感谢您的帮助!



如果我在调用python脚本之前导出LD_LIBRARY_PATH,一切都可行,但是我希望python来确定路径并设置en veroment变量为正确值)

解决方案

bash:

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

类似于Python:

  import os 
import subprocess
import sys

os.environ ['LD_LIBRARY_PATH'] =my_path#在此进程中可见*所有子项
subprocess.check_call(['sqsub','-np',sys.argv [1] '/ path / to / executable'],
env = dict(os.environ,SQSUB_VAR =在此子进程中可见)


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)

解决方案

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"))

这篇关于在python脚本中设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:39