在 Python 中循环导入字典

Import dictionary in loop in Python

我的问题与此有关。我有一个 config_file 由字典组成,如下所示:

config_1 = {
    'folder': 'raw1',
    'start_date': '2019-07-01'
}
config_2 = {
    'folder': 'raw2',
    'start_date': '2019-08-01'
}
config_3 = {
    'folder': 'raw3',
    'start_date': '2019-09-01'
}

然后我有一个单独的 python 文件导入每个配置并做一些事情:

from config_file import config_1 as cfg1
Do some stuff using 'folder' and 'start_date'

from config_file import config_2 as cfg2
Do some stuff using 'folder' and 'start_date'

from config_file import config_2 as cfg3
Do some stuff using 'folder' and 'start_date'

我想把它放在一个循环中,而不是在 python 文件中列出 3 次。我怎样才能做到这一点?

您可以使用检查模块从配置中获取所有可能的导入,如下所示。

import config
import inspect

configs = [member[1] for member in inspect.getmembers(config) if 'config_' in member[0]]

configs

然后您可以遍历所有配置,这是您想要的行为吗?

您可以阅读有关检查的更多信息here

.

如果我正确理解你的问题,请使用 importlib。简而言之,你在 python 中写的是什么:

from package import module as alias_mod

在 importlib 中变成:

alias_mod = importlib.import_module('module', 'package')

或者,等价地:

alias_mod = importlib.import_module('module.package')

例如:

from numpy import random as rm

在导入库中:

rm = importlib.import_module('random', 'numpy')

另一个有趣的事情是 this post 中提出的这段代码,它允许您不仅导入模块和包,还可以直接导入函数等等:

def import_from(module, name):
    module = __import__(module, fromlist=[name])
    return getattr(module, name)

对于您的具体情况,此代码应该有效:

import importlib

n_conf = 3
for in range(1, n_conf)
    conf = importlib.import_module('config_file.config_'+str(i))
    # todo somethings with conf 

但是,如果我能给你一些建议,我认为对你来说最好的办法是构建一个 json 配置文件并读取该文件而不是导入模块。舒服多了。例如,在您的情况下,您可以创建一个 config.json 文件,如下所示:

{
    "config_1": {
        "folder": "raw1",
        'start_date': '2019-07-01'
    },
    "config_2": {
        'folder': 'raw2',
        'start_date': '2019-08-01'
    },
    "config_3": {
        'folder': 'raw3',
        'start_date': '2019-09-01'
    }
}

读取json文件如下:

import json
with open('config.json') as json_data_file:
    conf = json.load(json_data_file)

现在你在内存中有了一个简单的 python 字典,其中包含你感兴趣的配置设置:

conf['config_1']
# output: {'folder': 'raw1', 'start_date': '2019-07-01'}

根据@MikeMajara 的评论,以下解决方案对我有用:

package = 'config_file'
configs = ['config_1', 'config_2', 'config_3']
for i in configs:
    cfg = getattr(__import__(package, fromlist=[configs]), i)
    Do some stuff using 'folder' and 'start_date'