在python中设置调用bash脚本的环境变量
我有一个如下所示的bash脚本:
I have a bash script that looks like this:
python myPythonScript.py
python myOtherScript.py $VarFromFirstScript
和myPythonScript.py
看起来像这样:
print("Running some code...")
VarFromFirstScript = someFunc()
print("Now I do other stuff")
问题是,如何将变量VarFromFirstScript
返回到名为myPythonScript.py
的bash脚本.
The question is, how do I get the variable VarFromFirstScript
back to the bash script that called myPythonScript.py
.
我尝试了os.environ['VarFromFirstScript'] = VarFromFirstScript
,但这是行不通的(我认为这意味着python环境与调用bash脚本的环境是不同的).
I tried os.environ['VarFromFirstScript'] = VarFromFirstScript
but this doesn't work (I assume this means that the python environment is a different env from the calling bash script).
您不能将环境变量传播到父进程.但是您可以打印该变量,然后从您的shell中将其分配回变量名称:
you cannot propagate an environment variable to the parent process. But you can print the variable, and assign it back to the variable name from your shell:
VarFromFirstScript=$(python myOtherScript.py $VarFromFirstScript)
您不得在代码中或使用stderr
you must not print anything else in your code, or using stderr
sys.stderr.write("Running some code...\n")
VarFromFirstScript = someFunc()
sys.stdout.write(VarFromFirstScript)
另一种选择是创建一个带有要设置的变量的文件,并由您的外壳程序对其进行解析(您可以创建一个其父外壳程序将为source
的外壳程序)
an alternative would be to create a file with the variables to set, and make it parse by your shell (you could create a shell that the parent shell would source
)
import shlex
with open("shell_to_source.sh","w") as f:
f.write("VarFromFirstScript={}\n".format(shlex.quote(VarFromFirstScript))
(shlex.quote
允许避免从python注入代码,由Charles Duffy提供)
(shlex.quote
allows to avoid code injection from python, courtesy Charles Duffy)
然后在调用python之后:
then after calling python:
source ./shell_to_source.sh