subprocess bash 脚本不会全局修改环境变量

subprocess bash script doesn't modify environment variables globally

我有一个 bash 脚本,它分配了几个环境变量。作为一个更简单的例子,我们可能有类似

export A=a

这个脚本叫做exporter.sh

我正在尝试使用 subprocess.run 从 python 中 运行 这个脚本。以下 python 脚本 运行 是导出器脚本并检查环境变量是否已正确设置:

import subprocess

subprocess.run("bash exporter.sh", shell=True)

print(subprocess.run(
    "echo $A",
    stdout=subprocess.PIPE,
    shell=True,
).stdout.decode('utf-8'))

然而,这 return 没有任何作用。如何在 python 中全局设置 bash 环境变量?

每个 subprocess.run 都有自己的(新)shell。在您的原始代码中:

  1. subprocess.run 打开一个 sh shell(subprocess 的默认值)。
  2. sh 打开一个 bash shell 并设置变量(在 bash shell 内)。
  3. bashshshell都关闭了(因为你的第一个subprocess.run命令完成了)和新设置的环境。变量被销毁。
  4. echo $A 在新的 sh shell 中启动,它不知道以前的 shell 有变量。

您可以 运行 'setter' 和 'getter' 在同一个 bash shell.

exporter.sh:

export A=b_set_from_exporter.sh

python 脚本:

import subprocess
cmd = "bash -c 'source ./exporter.sh && echo $A'"
print(subprocess.run(
    cmd,
    stdout=subprocess.PIPE,
    shell=True
).stdout.decode('utf-8'))

输出:

b_set_from_exporter.sh

注:

如果你真的需要设置变量全局和可访问(和永远)在多个 bash shells 共享,在 ~/.profile/etc/profile 中设置它们.