如何使用 argsparse 访问 python 中的部分配置文件?

How to use argsparse to access part of a config file in python?

我有这个 config.py 文件:

# config.py 

maria = dict(
    corners = [1,2,3,4],
    area = 2100
)

john = dict(
        corners = [5,6,7,8],
        area = 2400 
    )

并想通过 运行 使用 argsparse 连接我的主程序来使用它的参数。有点像这样:

# main.py

import config
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("user", help="maria or john")
args = parser.parse_args()
print(args.user)
print(config.args.user['corners'])

当我 运行:

pyhton3 main.py maria

我在第二次打印时遇到语法错误,我想得到 [1,2,3,4]。 如何使用 argparse 中的参数作为属性来访问配置文件中的适当数据?

IIUC: 您可以在 python.

中使用 getattr 内置函数

getattr(object, name[, default]):

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not >exist, default is returned if provided, otherwise AttributeError is raised.

替换:

print (config.args.user['corners'])

搭配:

print(getattr(config, args.user)["corners"])

解决这个问题的一种方法是将您的参数包装在一个通用字典中:

# config.py

params = {'maria': {'corners': [1,2,3,4], 'area': 2100},
          'john':  {'corners': [5,6,7,8], 'area': 2400}}

然后你可以简单地在 main.py:

print(config.params[args.user]['corners'])

避免使用可执行 Python 代码进行配置。使用类似 JSON:

config.json 看起来像

{
    "maria": {
        "corners": [1,2,3,4],
        "area": 2100
    },
    "john": {
        "corners": [5,6,7,8],
        "area": 2400
    }
}

您的脚本将使用

# main.py

import json
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("user", help="maria or john")
args = parser.parse_args()
with open("config.json") as f:
    config = json.load(f)

print(args.user)
print(config[args.user]['corners'])