Python 从环境文件中读取环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40216311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:18:00  来源:igfitidea点击:

Reading in environment variables from an environment file

pythondocker

提问by Kurt Peek

I'd like to run in a local environment a Python script which is normally run in a Docker container. The docker-compose.ymlspecifies an env_filewhich looks (partially) like the following:

我想在本地环境中运行一个通常在 Docker 容器中运行的 Python 脚本。在docker-compose.yml指定了一个env_file像下面看上去(部分):

DB_ADDR=rethinkdb
DB_PORT=28015
DB_NAME=ipercron

In order to run this locally, I would like these lines to be converted to

为了在本地运行,我希望将这些行转换为

os.environ['DB_ADDR'] = 'rethinkdb'
os.environ['DB_PORT'] = '28015'
os.environ['DB_NAME'] = 'ipercron'

I could write my parser, but I was wondering if there are any existing modules/tools to read in environment variables from configuration files?

我可以编写我的解析器,但我想知道是否有任何现有的模块/工具可以从配置文件中读取环境变量?

回答by Moinuddin Quadri

You can use ConfigParser. Sample example can be found here.

您可以使用ConfigParser. 示例示例可以在这里找到。

But this library expects your key=valuedata to be present under some [heading]. For example, like:

但是这个库希望你的key=value数据出现在一些[heading]. 例如,像:

[mysqld]
user = mysql  # Key with values
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb      # Key without value
skip-innodb

回答by radtek

This could also work for you:

这也适用于您:

env_vars = []
with open(env_file) as f:
    for line in f:
        if line.startswith('#') or not line.strip():
            continue
        # if 'export' not in line:
        #     continue
        # Remove leading `export `, if you have those
        # then, split name / value pair
        # key, value = line.replace('export ', '', 1).strip().split('=', 1)
        key, value = line.strip().split('=', 1)
        # os.environ[key] = value  # Load to local environ
        env_vars.append({'name': key, 'value': value}) # Save to a list

print(env_vars);

In the comments you'll find a few different ways to save the env vars and also a few parsing options i.e. to get rid of leading exportkeyword. Another way would be to use the python-dotenvlibrary. Cheers.

在评论中,您会发现几种不同的方法来保存环境变量以及一些解析选项,即摆脱前导export关键字。另一种方法是使用python-dotenv库。干杯。

回答by h0tw1r3

Using only python std

仅使用 python std

import re

envre = re.compile(r'''^([^\s=]+)=(?:[\s"']*)(.+?)(?:[\s"']*)$''')
result = {}
with open('/etc/os-release') as ins:
    for line in ins:
        match = envre.match(line)
        if match is not None:
            result[match.group(1)] = match.group(2)

回答by ParisNakitaKejser

I will use https://pypi.org/project/python-dotenv/just type pip install python-dotenvand then in your code you can use

我将使用https://pypi.org/project/python-dotenv/只需键入pip install python-dotenv然后在您的代码中您就可以使用

from dotenv import load_dotenv
load_dotenv()

this is the way i do when i need to test code outside my docker system, and prepare it to return it into docker again.

当我需要在我的 docker 系统之外测试代码并准备将它再次返回到 docker 时,我就是这样做的。

回答by Dewald Abrie

How about this for a more compact solution:

对于更紧凑的解决方案如何:

import os

with open('.docker-compose-env', 'r') as fh:
    vars_dict = dict(
        tuple(line.split('='))
        for line in fh.readlines() if not line.startswith('#')
    )

print(vars_dict)
os.environ.update(vars_dict)