【发布时间】:2020-04-05 00:49:44
【问题描述】:
操作系统:Mac OSX 10.14 Python 2.7
我有一个如下所示的 python 脚本:
#! /usr/bin/python
import os
os.system('./binaryfileproducesenv_variables > ./env_variables_file')
os.system('chmod 744 ./env_variables_file')
os.system('./env_variables_file')
os.system('python anotherpythonscript.py')
env_variables_file 如下所示:
passwordA='abcd';
passwordB='1234';
export passwordA passwordB
anotherpythonscript.py 只有在上面的环境变量设置正确的情况下才能正常工作。当我通过主 python 脚本运行它时,它没有定义变量。虽然,如果我直接从命令行运行 ./env_variables_file ,它将设置环境变量。关于如何通过 Python 脚本运行并设置环境变量的任何建议。
【问题讨论】:
-
os.system('python anotherpythonscript.py')- 你为什么要这样做?你为什么不把它作为一个模块导入并运行 main 函数(如果它被设计为作为脚本运行并且有if __name__="__main__": main())? -
stackoverflow.com/questions/5971312/… 我想这回答了你的问题
-
我正在研究使用 os.environment,但是 env_variables_file 是一个新创建的文件,每次我们想要运行 anotherpythonscript.py 脚本时都需要创建(使用新的环境密码)
-
如果你在 python 脚本中只使用
os.system那么你应该创建 bash 脚本。您将拥有相同的命令,但没有os.system -
os.system('./env_variables_file')不会像您认为的那样做。运行脚本会在一个子 shell 中设置导出。您需要阅读该文件,并在调用下一个脚本之前使用os.environ单独设置每个变量。也就是说:只需制作一个 bash 包装器而不是 python 包装器,从而降低复杂性和执行时间。
标签: python linux variables operating-system environment-variables