python - 使 argparse 处理破折号和下划线相同
问题描述
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
作为定义此可选参数的有效方法?
解决方案
parser.add_argument
一个参数接受多个标志(链接到文档)。使解析器接受这两种变体的一种简单方法是将参数声明为
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
to _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
(来自CPython实现here)中的相应方法。使用这个子类应该使可选参数的匹配与使用破折号-
或下划线保持一致_
。
推荐阅读
- html - 在 FullCalendar 上选择日期时,点击精度校准错误
- node.js - 纱线 2 - YN0027:react@unknown 无法解析到令人满意的范围:
- java - Android Studio - 在 Y 坐标上获取屏幕底部的 5th
- c# - 向数据库表添加新记录时出现异常未处理
- javascript - 他们不会加载 glider-js 在 nextjs 中创建的 div 内的元素
- java - 我正在制作一个程序来模拟战争游戏,但是在尝试获取随机卡片时,我总是随机出现错误
- javascript - 如何使用 puppeteer 单击列表中的特定元素?
- next.js - Next.js - 不同的获取类型方法
- c++ - 显式构造函数不是候选者
- javascript - Safari:在滚动时使用 css 动画时抖动的文本