argparse
用下划线替换可选参数中的破折号,以确定其目的地:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--use-unicorns', action='store_true')
args = parser.parse_args(['--use-unicorns'])
print(args) # returns: Namespace(use_unicorns=True)
但是,用户必须记住该选项是--use-unicorns
还是--use_unicorns
;使用错误的变体会引发错误。
这会引起一些挫败感,因为代码中的变量args.use_unicorns
不能清楚地定义了哪个变量。
如何使argparse
接受--use-unicorns
和--use_unicorns
作为定义此可选参数的有效方法?
答案 0 :(得分:0)
parser.add_argument
接受一个参数(link to documentation)的多个标志。使解析器接受两个变体的一种简单方法是将参数声明为
parser.add_argument('--use-unicorns', '--use_unicorns', action='store_true')
但是,这两个选项都会显示在帮助中,并且它不是很优雅,因为它迫使人们手动编写变体。
另一种方法是继承argparse.ArgumentParser
的子类,以使匹配不变式变为用下划线替换破折号。这需要一点点摆弄,因为argparse_ActionsContainer._parse_optional
和argparse_ActionsContainer._get_option_tuples
都必须修改以处理这种匹配和缩写,例如--use_unic
。
我最终得到了以下子类化方法,其中缩写的匹配从_parse_optional
委托给_get_option_tuples
:
from gettext import gettext as _
import argparse
class ArgumentParser(argparse.ArgumentParser):
def _parse_optional(self, arg_string):
# if it's an empty string, it was meant to be a positional
if not arg_string:
return None
# if it doesn't start with a prefix, it was meant to be positional
if not arg_string[0] in self.prefix_chars:
return None
# if it's just a single character, it was meant to be positional
if len(arg_string) == 1:
return None
option_tuples = self._get_option_tuples(arg_string)
# if multiple actions match, the option string was ambiguous
if len(option_tuples) > 1:
options = ', '.join([option_string
for action, option_string, explicit_arg in option_tuples])
args = {'option': arg_string, 'matches': options}
msg = _('ambiguous option: %(option)s could match %(matches)s')
self.error(msg % args)
# if exactly one action matched, this segmentation is good,
# so return the parsed action
elif len(option_tuples) == 1:
option_tuple, = option_tuples
return option_tuple
# if it was not found as an option, but it looks like a negative
# number, it was meant to be positional
# unless there are negative-number-like options
if self._negative_number_matcher.match(arg_string):
if not self._has_negative_number_optionals:
return None
# if it contains a space, it was meant to be a positional
if ' ' in arg_string:
return None
# it was meant to be an optional but there is no such option
# in this parser (though it might be a valid option in a subparser)
return None, arg_string, None
def _get_option_tuples(self, option_string):
result = []
if '=' in option_string:
option_prefix, explicit_arg = option_string.split('=', 1)
else:
option_prefix = option_string
explicit_arg = None
if option_prefix in self._option_string_actions:
action = self._option_string_actions[option_prefix]
tup = action, option_prefix, explicit_arg
result.append(tup)
else: # imperfect match
chars = self.prefix_chars
if option_string[0] in chars and option_string[1] not in chars:
# short option: if single character, can be concatenated with arguments
short_option_prefix = option_string[:2]
short_explicit_arg = option_string[2:]
if short_option_prefix in self._option_string_actions:
action = self._option_string_actions[short_option_prefix]
tup = action, short_option_prefix, short_explicit_arg
result.append(tup)
underscored = {k.replace('-', '_'): k for k in self._option_string_actions}
option_prefix = option_prefix.replace('-', '_')
if option_prefix in underscored:
action = self._option_string_actions[underscored[option_prefix]]
tup = action, underscored[option_prefix], explicit_arg
result.append(tup)
elif self.allow_abbrev:
for option_string in underscored:
if option_string.startswith(option_prefix):
action = self._option_string_actions[underscored[option_string]]
tup = action, underscored[option_string], explicit_arg
result.append(tup)
# return the collected option tuples
return result
许多此类代码直接来自argparse
(from the CPython implementation here)中的相应方法。使用此子类应该使可选参数的匹配与使用破折号-
或下划线_
不变。
答案 1 :(得分:0)
parser.add_argument('--use-unicorns', action='store_true')
args = parser.parse_args(['--use-unicorns'])
print(args) # returns: Namespace(use_unicorns=True)
argparse
将'-'转换为'_',因为在标记中使用'-'是POSIX的惯例。但是args.use-unicones
是不可接受的Python。换句话说,它会进行翻译,因此dest
将是有效的Python变量或属性名称。
请注意,argparse
不会对positionals
执行此翻译。在这种情况下,程序员可以完全控制dest
参数,并可以选择任何方便的方法。由于argparse
在访问getattr
时仅使用setattr
和Namespace
,因此对有效dest
的约束是最小的。
有两个用户。有你,程序员,还有你的最终用户。对您来说方便的方法可能对其他方法不是最佳选择。
您还可以通过定义dest
来指定optional
。并且metavar
使您可以进一步控制help
的显示。
parser._get_optional_kwargs
执行'-'替换:
if dest is None:
....
dest = dest.replace('-', '_')