在python中设置调用bash脚本的环境变量 [英] Set environment variable of calling bash script in python

查看:557
本文介绍了在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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆