我创建一个像这样的ArgumentParser:
argpr = ArgumentParser()
argpr.add_argument('--long-c', '-c', required=True, dest='long_c')
如果存在json configfile,则将配置添加到命名空间:
cfg = argparse.Namespace()
if json_dict is not None:
cfg.long_c = json['long-c']
print vars(cfg)
然后,我使用命名空间作为参数解析器的参数,如下所示:
use_cfg = argpr.parse_args(namespace=cfg)
我可以看到我在Namespace对象中获得了一个值,因此,我期望ArgumentParser.parse_args在我的Namespace对象中找到long_c,但是得到:
argument --long-c/-c is required
难道我做错了什么?这是错误还是预期的行为?欢迎任何有关如何实现此工作的建议=)
先感谢您
编辑:
-修正错别字。
-将名称空间更改为“名称空间”对象。
-阐明了我对命名空间对象的使用和期望。
python大神给出的解决方案
我将ArgumentParser
细分为您要执行的操作。
import json
from argparse import ArgumentParser
class ConfigurableArgumentParser(ArgumentParser):
def __init__(self, config_file, *args, **kwargs):
self.config = json.load(config_file)
super(ConfigurableArgumentParser, self).__init__(*args, **kwargs)
def add_argument(self, *args, **kwargs):
store_action = super(ConfigurableArgumentParser, self).add_argument(
*args, **kwargs)
dest = store_action.dest
if dest in self.config:
store_action.default = self.config[dest]
store_action.required = False
return store_action
该参数解析器采用附加的构造函数参数config_file
,该参数应该是指向JSON配置文件的文件对象。将add_argument
方法修改为使用配置文件中的默认值(如果存在),在这种情况下,required
也将设置为False
。
用法:
if __name__ == '__main__':
from StringIO import StringIO
# config_file = open('my_config.json')
config_file = StringIO('{"long_c": "1"}')
parser = ConfigurableArgumentParser(config_file)
parser.add_argument('--long-c', '-c',
required=True, dest='long_c', type=int)
namespace = parser.parse_args()
print namespace
# Output:
# Namespace(long_c=1)
请注意,该类型仍然按照应有的方式进行处理,并且JSON字符串会自动转换为int
。