简体   繁体   English

采购文件以从python脚本中设置环境变量

[英]Sourcing a file to set environment variables from within a python script

Running on Ubuntu, I have a python script, written by someone else, which simply runs like this: 在Ubuntu上运行,我有一个由其他人编写的python脚本,其运行方式如下:

python cool_script.py command line args

However, this script needs some environment variables set before it can run. 但是,此脚本需要设置一些环境变量才能运行。 So I created exports.sh located in the same dir as the python script, which looks something like: 因此,我在与python脚本相同的目录中创建了exports.sh ,如下所示:

export ENV1='foo'
export ENV2='bar'
export ENV3='baz'

so running: 这样运行:

$source exports.sh
$python cool_script.py command line args

works great. 效果很好。 However, my case is a bit more complex. 但是,我的情况要复杂一些。 I need to run this on several environments, where the values of ENV1,ENV2,ENV3 will have to be different. 我需要在几个环境中运行此环境,其中ENV1,ENV2,ENV3的值必须不同。 I also want to do some stuff to the outputs of cool_script.py . 我还想对cool_script.py的输出进行cool_script.py So I wrote cool_script_wrapper.py , which looks like this: 所以我写了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
...

I was planning to have different exports.sh scripts for each environment I need to run on, always keeping them in the same dir as the main script. 我计划为需要在每个环境上运行的每个环境使用不同的exports.sh脚本,并始终将它们与主脚本保持在相同的目录中。 Only problem is that this 'source' approach doesn't work. 唯一的问题是这种“源”方法不起作用。 The environment variables are simply not available to cool_script.py . 这些环境变量根本无法用于cool_script.py
Searching around Stack Overflow, I understand now that it's not supposed to work, but I didn't find any solution that suits my needs. 搜寻Stack Overflow,我现在知道它不起作用,但是没有找到适合我需求的解决方案。 I don't want to use os.environ with hard-coded values, and I don't want to parse the exports file. 我不想将os.environ与硬编码的值一起使用,也不想解析导出文件。 I guess I could make my wrapper a bash script rather than a python, but I hope there is a better solution. 我想我可以使包装器成为bash脚本而不是python,但我希望有更好的解决方案。 Any ideas? 有任何想法吗?

The problem is in the source command that attempts to call a bash builtin. 问题出在试图调用内置bash的source命令中。 This should work: 这应该工作:

import os
os.environ['ENV1'] = "foo"
os.system("python cool_script.py command line args")

compare with this answer: Calling the "source" command from subprocess.Popen 与以下答案进行比较: 从subprocess.Popen调用“源”命令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM