简体   繁体   English

如何从操作系统环境变量创建字典?

[英]How to create a dictionary from OS environment variables?

There are environment variables set in the operating system (macos):操作系统(macos)中设置了环境变量:

MYSQL_HOST="127.0.0.1"
MYSQL_DATABASE="invoice"
MYSQL_UID="dude"
MYSQL_PWD="pass1234"

I would like to build a list called db_config such that the end result will look like:我想建立一个名为db_config的列表,最终结果将如下所示:

db_config = {'host':"127.0.0.1", 'database':"invoice", 'user':"dude",
             'password':"pass1234"}

(Note that the environment variable names differ from the keys in db_config . db_config will be used to pass database connection credentials, and the keys must be those listed in the above db_config .) (请注意,环境变量名称与db_config中的键不同db_config将用于传递数据库连接凭据,并且键必须是上述db_config中列出的那些。)

I can "manually" set db_config using:我可以“手动”设置db_config使用:

db_config={'host':os.environ['MYSQL_HOST'], 'database':os.environ['MYSQL_DATABASE'],
           'user':os.environ['MYSQL_UID'], 'password':os.environ['MYSQL_PWD']}

...but it seems like there should be a cleaner more pythonic way of doing this, but I can't figure it out. ...但似乎应该有一种更清洁、更 Pythonic 的方式来做到这一点,但我想不通。

config = {
    'host': 'MYSQL_HOST',
    'database': 'MYSQL_DATABASE',
    'user': 'MYSQL_UID',
    'password': 'MYSQL_PWD'
}
db_config = {k: os.environ.get(v) for k, v in config.items()}

Depending on how you want to treat items that aren't in os.environ , you can use a conditional dict comprehension to ignore them.根据您希望如何处理不在os.environ中的项目,您可以使用条件字典理解来忽略它们。

db_config = {k: os.environ.get(v) for k, v in config.items()
             if v in os.environ}

You may wish to rename old_name and new_name in the code below;您可能希望在下面的代码中重命名old_namenew_name and if you are sure that the environment variables will be present or require them to be available for your code to work correctly, you can remove the if section of the dictionary comprehension shown below:如果您确定环境变量将存在或要求它们可用于您的代码正常工作,您可以删除字典理解的if部分,如下所示:

import os

transformations = (
    ('MYSQL_HOST', 'host'),
    ('MYSQL_DATABASE', 'database'),
    ('MYSQL_UID', 'user'),
    ('MYSQL_PWD', 'password')
)

db_config = {
    new_name: os.environ[old_name]
    for old_name, new_name in transformations
    if old_name in os.environ
}

all ENV variable related to MYSQL in one dict一个字典中与 MYSQL 相关的所有 ENV 变量

import os

keys = dict(os.environ).keys()

dic = {}
for key in keys:
    if 'MYSQL_' in key:
        dic.update({key.split('MYSQL_')[1]:os.environ.get(key)})

print(dic)      

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

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