在Ubuntu上运行,我有一个python脚本,由其他人编写,其运行方式如下:
python cool_script.py command line args
但是,此脚本在运行之前需要设置一些环境变量。所以我创建了exports.sh
位于与python脚本相同的目录中,它看起来像:
export ENV1='foo'
export ENV2='bar'
export ENV3='baz'
所以跑步:
$source exports.sh
$python cool_script.py command line args
效果很好。但是,我的情况有点复杂。我需要在几个环境中运行它,其中ENV1,ENV2,ENV3的值必须不同。我还想对cool_script.py
的输出做一些事情。所以我写了cool_script_wrapper.py
,看起来像这样:
# set environment variables
import os
exports_file = os.path.dirname(os.path.realpath(__file__)) + '/exports.sh'
os.system('source %s' % exports_file)
# run cool_script.py
os.system('python cool_script.py command line args')
# do some stuff to the output
...
我计划为每个需要运行的环境使用不同的exports.sh
脚本,始终将它们保存在与主脚本相同的目录中。唯一的问题是这个来源'方法不起作用。环境变量根本不适用于cool_script.py
搜索Stack Overflow,我现在明白它不应该工作,但我找不到任何适合我需要的解决方案。我不想将os.environ
与硬编码值一起使用,我也不想解析导出文件。我想我可以使我的包装器成为bash脚本而不是python,但我希望有更好的解决方案。有什么想法吗?
答案 0 :(得分:0)