导致 Python 的 argparse 执行默认操作 [英] Cause Python's argparse to execute action for default
问题描述
我正在使用 argparse 的操作向类添加各种数据.如果命令行未提供该参数,我想对默认值使用该操作.这可能吗?谢谢!
I am using argparse's action to add various data to a class. I would like to use that action on the default value if that arg is not provided at the command line. Is this possible? Thanks!
推荐答案
argparse
在应用 default
时不使用 action
.它只使用 setattr
.如果默认值是字符串,则它可以使用 type
.但是你可以直接调用action
.
argparse
does not use the action
when applying the default
. It just uses setattr
. It may use the type
if the default is a string. But you can invoke the action
directly.
这里我使用了从文档中借来的自定义操作类.在第一个 parse_args
中什么也没有发生.然后我创建一个新的 namespace
,并调用默认操作.然后我将该命名空间传递给 parse_args
.要理解这一点,您需要将其导入交互式 shell,并检查命名空间和操作的属性.
Here I use a custom action class borrowed from the documentation. In the first parse_args
nothing happens. Then I create a new namespace
, and invoke the action on the default. Then I pass that namespace to parse_args
. To understand this, you many need to import it into an interactive shell, and examine the attributes of the namespace and action.
# sample custom action from docs
class FooAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print('Setting: %r %r %r' % (namespace, values, option_string))
setattr(namespace, self.dest, 'action:'+values)
p = argparse.ArgumentParser()
a1 = p.add_argument('--foo', action=FooAction, default='default')
print 'action:',a1
print p.parse_args([])
ns = argparse.Namespace()
a1(p, ns, a1.default, 'no string') # call action
print p.parse_args([],ns)
print p.parse_args(['--foo','1'],ns)
产生:
action: FooAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default='default', type=None, choices=None, help=None, metavar=None)
Namespace(foo='default')
Setting: Namespace() 'default' 'no string'
Namespace(foo='action:default')
Setting: Namespace(foo='action:default') '1' '--foo'
Namespace(foo='action:1')
我调整了输出,以突出显示正在使用的操作.
I tailored the output to highlight when the action is being used.
这里有一种对命令行中没有给出的参数执行特殊操作的方法(或者给定值 == 到默认值).这是 https://stackoverflow.com/a/24638908/901925 中给出的类的简化.
Here's a way of performing a special action on an argument that isn't given on the command line (or given with a value == to the default). It's a simplification of the class given in https://stackoverflow.com/a/24638908/901925.
class Parser1:
def __init__(self, desc):
self.parser = argparse.ArgumentParser(description=desc)
self.actions = []
def milestone(self, help_='milestone for latest release.', default=None):
action = self.parser.add_argument('-m', '--milestone', help=help_, default=default)
self.actions.append(action)
return self
def parse(self):
args = self.parser.parse_args()
for a in self.actions:
if getattr(args, a.dest) == a.default:
print 'Please specify', a.dest
values = raw_input('>')
setattr(args, a.dest, values)
return args
print Parser1('desc').milestone(default='PROMPT').parse()
提示在parse_args
之后完成.我看不出有什么理由再次调用 parse_args
.
The prompting is done after parse_args
. I don't see any reason to call parse_args
again.
这篇关于导致 Python 的 argparse 执行默认操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!