python - 设置python调用bash脚本的环境变量

标签 python bash environment-variables

我有一个如下所示的 bash 脚本:

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 脚本.

我试过os.environ['VarFromFirstScript'] = VarFromFirstScript但这不起作用(我认为这意味着 python 环境与调用 bash 脚本的环境不同)。

最佳答案

您无法将环境变量传播到父进程。但是您可以打印该变量,并将其从 shell 分配回变量名称:

VarFromFirstScript=$(python myOtherScript.py $VarFromFirstScript)

您不得在代码中打印任何其他内容,或使用 stderr

sys.stderr.write("Running some code...\n")
VarFromFirstScript = someFunc()
sys.stdout.write(VarFromFirstScript)

另一种方法是创建一个包含要设置的变量的文件,并使其由您的 shell 进行解析(您可以创建一个父 shell 会的 shell)

import shlex
with open("shell_to_source.sh","w") as f:
   f.write("VarFromFirstScript={}\n".format(shlex.quote(VarFromFirstScript))

(shlex.quote 允许避免来自 python 的代码注入(inject),由 Charles Duffy 提供)

然后调用 python 后:

source ./shell_to_source.sh

关于python - 设置python调用bash脚本的环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49201028/

相关文章:

bash - 如何在 TCL 中使用 exec 将变量拆分为两个参数?

linux - 意外标记附近的语法错误 `}'

json - 如何让 cURL 仅输出 HTTP 响应正文(JSON)而不输出其他 header 等

windows - 如何在 Windows 批处理文件中检索 P4 ROOT 变量值?

python - 计算样本的标准偏差

python - QLabel 不会重新绘制像素图

python - 如何在 Python 中设置父 shell 的环境变量?

ubuntu - 无法在 Ubuntu 中设置 flutter 环境变量

python - 无法捕获模拟异常,因为它不继承 BaseException

python - 矩形未绘制在屏幕上