使用 argparse 模块,是否可以对给定参数执行多个操作?
argparse
具体来说,我想提供 -l / --list 选项与 nargs='?' 这将改变程序的行为,使其从主要功能变为提供有关集合中所有可能性或特定可能性的信息。
-l
--list
nargs='?'
通常会有一个名称空间属性,它包含一个要在解析后调用的函数;我希望 -L 选项可以同时更改此属性,也可以选择将其参数存储在其他属性中。
-L
这有可能吗?
只需实现自己的 Action 子类。基本上是这样的:
Action
class ListAction(argparse.Action): def __call__(parser, namespace, values, option_string=None): setattr(namespace, 'list', values[0]) do_something_completely_different()
这个 argparse documentation 有更多详细信息。