传递范围配置的最佳方式

问题描述 投票:0回答:1

我有一个绘图函数,可用于多种用途。我绘制曲线的方式是相同的,但我需要根据我正在绘制的数据自定义限制和标签。 现在我在字典中定义设置,然后像这样读取它们

for d in data_keys:
    data = np.load(...) 
    ax.plot(data, label=data_to_label[d])
    ax.xaxis.set_ticks(data_to_xticks[d])
    ax.set_xlim([0, data_to_xlim[d]])

等等,我需要的其他东西。

字典是这样的

data_to_label = {
    'easy' : 'Alg. 1 (Debug)',
    'hard' : 'Alg. 2',
}

data_to_xlim = {
    'easy' : 500,
    'hard' : 2000,
}

data_to_xticks = {
    'easy' : [0, 250, 500],
    'hard' : np.arange(0, 2001, 500),
}

data_to_ylim = {
    'easy' : [-0.1, 1.05],
    'hard' : [-0.1, 1.05],
}

data_to_yticks = {
    'Easy' : [0, 0.5, 1.],
    'hard' : [0, 0.5, 1.],
}

我有很多这些,我正在寻找将它们保存在配置文件中并将它们加载到我的绘图函数中的最佳方法。我考虑过 Hydra、YAML、JSON,但没有一个允许指定

np.arange()
作为参数。 理想情况下,当我调用
python myplot.py
时,我可以将配置文件作为参数传递。

我也可以导入它们,但是必须从传递给

myplot.py
的字符串中读取导入。

python json yaml arguments hydra
1个回答
0
投票

我也可以导入它们,但是必须从传递给

myplot.py

的字符串中读取导入

如果您信任要导入的模块,这可能是个好主意。您可以使用

argparse
importlib
inspect
模块来做到这一点:

myplot.py

import argparse
import importlib
import inspect

def myplot_function():
    # do stuff here
    print(data_to_label)
    print(data_to_xlim)
    print(data_to_xticks)
    print(data_to_ylim)
    print(data_to_yticks)


if __name__ == '__main__':
    # simple cli
    parser = argparse.ArgumentParser(prog='myplot')
    parser.add_argument('-c', '--config')
    args = parser.parse_args()

    # inject dictionaries into the global namespace
    cfgmod = importlib.import_module(inspect.getmodulename(args.config))
    dicts = {k: v for k, v in inspect.getmembers(cfgmod)
             if isinstance(v, dict) and not k.startswith('_')}
    globals().update(**dicts)

    myplot_function()

用途:

[...]$ python myplot.py -c config.py
{'easy': 'Alg. 1 (Debug)', 'hard': 'Alg. 2'}
{'easy': 500, 'hard': 2000}
{'easy': [0, 250, 500], 'hard': array([   0,  500, 1000, 1500, 2000])}  # <- HERE
{'easy': [-0.1, 1.05], 'hard': [-0.1, 1.05]}
{'easy': [0, 0.5, 1.0], 'hard': [0, 0.5, 1.0]}

config.py

import numpy as np

data_to_label = {
    'easy' : 'Alg. 1 (Debug)',
    'hard' : 'Alg. 2',
}

data_to_xlim = {
    'easy' : 500,
    'hard' : 2000,
}

data_to_xticks = {
    'easy' : [0, 250, 500],
    'hard' : np.arange(0, 2001, 500),
}

data_to_ylim = {
    'easy' : [-0.1, 1.05],
    'hard' : [-0.1, 1.05],
}

data_to_yticks = {
    'easy' : [0, 0.5, 1.],
    'hard' : [0, 0.5, 1.],
}
© www.soinside.com 2019 - 2024. All rights reserved.