argparse按需进口的类型,选择等 [英] argparse on demand imports for types, choices etc

查看:69
本文介绍了argparse按需进口的类型,选择等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的程序,它具有基于argparse的CLI交互,并带有多个子解析器. subparsers自变量支持的选项列表是根据数据库查询,解析不同的xml文件,进行不同的计算等确定的,因此它非常耗费IO和时间.

I have quite a big program which has a CLI interaction based on argparse, with several sub parsers. The list of supported choices for the subparsers arguments are determined based on DB queries, parsing different xml files, making different calculations etc, so it is quite IO intensive and time consuming.

问题在于,当我运行脚本时,argparse似乎为所有子解析器获取了choices,这增加了相当大且令人讨厌的启动延迟.

The problem is that argparse seems to fetch choices for all sub parser when I run the script, which adds a considerable and annoying startup delay.

是否有一种方法可以使argparse仅为当前使用的子解析器获取并验证choices?

Is there a way to make argparse only fetch and validate choices for the currently used sub parser?

一种解决方案可能是将所有验证逻辑都移到代码内部,但这意味着很多工作,如果可能的话,我想避免.

One solution could be to move all the validation logic deeper inside the code but that would mean quite a lot of work which I would like to avoid, if possible.

谢谢

推荐答案

要延迟获取选项,您可以分两个阶段解析命令行:在第一阶段,仅找到子解析器,在第二阶段阶段,子解析器用于解析其余参数:

To delay the fetching of choices, you could parse the command-line in two stages: In the first stage, you find only the subparser, and in the second stage, the subparser is used to parse the rest of the arguments:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('subparser', choices=['foo','bar'])

def foo_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('fooval', choices='123')
    return parser

def bar_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('barval', choices='ABC')
    return parser

dispatch = {'foo':foo_parser, 'bar':bar_parser}
args, unknown = parser.parse_known_args()
args = dispatch[args.subparser]().parse_args(unknown)
print(args)

它可以这样使用:

% script.py foo 2
Namespace(fooval='2')

% script.py bar A
Namespace(barval='A')

请注意,顶层帮助消息将不太友好,因为它只能告诉您有关子解析器的选择:

Note that the top-level help message will be less friendly, since it can only tell you about the subparser choices:

% script.py -h
usage: script.py [-h] {foo,bar}
...

要在每个子解析器中查找有关选择的信息,用户必须选择子解析器并将-h传递给它:

To find information about the choices in each subparser, the user would have to select the subparser and pass the -h to it:

% script.py bar -- -h
usage: script.py [-h] {A,B,C}

--之后的所有参数都被认为是非选项(script.py),因此被bar_parser解析.

All arguments after the -- are considered non-options (to script.py) and are thus parsed by the bar_parser.

这篇关于argparse按需进口的类型,选择等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆