argparse 参数顺序 [英] argparse argument order
本文介绍了argparse 参数顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个小问题.
我使用 argparse
来解析我的参数,而且效果很好.
为了获得参数,我这样做:
p_args = parser.parse_args(argv)args = dict(p_args._get_kwargs())
但是 p_args
的问题是我不知道如何让这些参数按它们在命令行中的位置排序,因为它是一个字典.
那么有没有可能在元组/列表/有序字典中按照命令行中的顺序来设置参数?
解决方案
为了使参数保持有序,我使用了这样的自定义操作:
导入 argparse类 CustomAction(argparse.Action):def __call__(self, parser, namespace, values, option_string=None):如果不是命名空间中的ordered_args":setattr(命名空间,'ordered_args',[])上一个 = namespace.ordered_argsprevious.append((self.dest, values))setattr(命名空间,'ordered_args',前一个)解析器 = argparse.ArgumentParser()parser.add_argument('--test1', action=CustomAction)parser.add_argument('--test2', action=CustomAction)
要使用它,例如:
<预><代码>>>>parser.parse_args(['--test2', '2', '--test1', '1'])命名空间(ordered_args=[('test2', '2'), ('test1', '1')], test1=None, test2=None)I have a little problem.
I use argparse
to parse my arguments, and it's working very well.
To have the args, I do :
p_args = parser.parse_args(argv)
args = dict(p_args._get_kwargs())
But the problem with p_args
is that I don't know how to get these arguments ordered by their position in the command line, because it's a dict.
So is there any possibility to have the arguments in a tuple/list/ordered dict by their order in the command line?
解决方案
To keep arguments ordered, I use a custom action like this:
import argparse
class CustomAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if not 'ordered_args' in namespace:
setattr(namespace, 'ordered_args', [])
previous = namespace.ordered_args
previous.append((self.dest, values))
setattr(namespace, 'ordered_args', previous)
parser = argparse.ArgumentParser()
parser.add_argument('--test1', action=CustomAction)
parser.add_argument('--test2', action=CustomAction)
To use it, for example:
>>> parser.parse_args(['--test2', '2', '--test1', '1'])
Namespace(ordered_args=[('test2', '2'), ('test1', '1')], test1=None, test2=None)
这篇关于argparse 参数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文