简体   繁体   English

从shell脚本加载环境变量

[英]Load environment variables from a shell script

I have a file with some environment variables that I want to use in a python script 我有一个文件,其中包含一些我想在python脚本中使用的环境变量

The following works form the command line 以下工作形成命令行

$ source myFile.sh
$ python ./myScript.py

and from inside the python script I can access the variables like 从python脚本里面我可以访问变量之类的

import os
os.getenv('myvariable')

How can I source the shell script, then access the variables, from with the python script? 我如何从python脚本中获取shell脚本,然后访问变量?

If you are saying backward environment propagation, sorry, you can't. 如果你说落后环境传播,抱歉,你不能。 It's a security issue. 这是一个安全问题。 However, directly source environment from python is definitely valid. 但是,python的直接源环境肯定是有效的。 But it's more or less a manual process. 但它或多或少是一个手动过程。

import subprocess as sp

SOURCE = 'your_file_path'
proc = sp.Popen(['bash', '-c', 'source {} && env'.format(SOURCE)], stdout=sp.PIPE)

source_env = {tup[0].strip(): tup[1].strip() for tup in map(lambda s: s.strip().split('=', 1), proc.stdout)}

Then you have everything you need in source_env . 然后,您在source_env拥有所需的一切。

If you need to write it back to your local environment (which is not recommended, since source_env keeps you clean): 如果您需要将其写回本地环境(不推荐使用,因为source_env会让您保持干净):

import os

for k, v in source_env.items():
    os.environ[k] = v

Another tiny attention needs to be paid here, is since I called bash here, you should expect the rules are applied here too. 这里需要付出另一个微小的关注,因为我在这里调用bash ,你应该期望这里也适用规则。 So if you want your variable to be seen, you will need to export them. 因此,如果您希望看到变量,则需要导出它们。

export VAR1='see me'
VAR2='but not me'

You can not load environmental variables in general from a bash or shell script, it is a different language. 无法通过bash或shell脚本加载环境变量,它是一种不同的语言。 You will have to use bash to evaluate the file and then somehow print out the variables and then read them. 您将不得不使用bash来评估文件,然后以某种方式打印出变量然后读取它们。 see Forcing bash to expand variables in a string loaded from a file 请参阅强制bash扩展从文件加载的字符串中的变量

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

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