像许多命令行工具一样,我的接受可选文件名。 Argparse 似乎通过 nargs='*'
支持这一点,正如预期的那样对我有用:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'files',
help='file(s) to parse instead of stdin',
nargs='*')
parser.parse_args()
但是,帮助输出很奇怪:$ ./help.py -h
usage: help.py [-h] [files [files ...]]
如何避免嵌套的可选和重复参数名称?除了 [files ...] 之外,重复不添加任何信息,这是 Unix 上指示可选参数列表的传统方式:$ grep --help
usage: grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
[-e pattern] [-f file] [--binary-files=value] [--color=when]
[--context[=num]] [--directories=action] [--label] [--line-buffered]
[--null] [pattern] [file ...]
$ ls --help
Usage:
exa [options] [files...]
$ vim --help
Usage:
nvim [options] [file ...] Edit file(s)
任何帮助表示赞赏。我正在尝试 argparse,因为使用它似乎是 Python 的最佳实践,但这个帮助输出对我来说是一个交易破坏者。
最佳答案
这已在 Python 3.9 中修复,请参阅 https://bugs.python.org/issue38438和 commit a0ed99bc
那修复了它。
如果在 3.9 上运行,您的代码会生成您期望的使用消息:
Python 3.9.0 (default, Oct 12 2020, 02:44:01)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('files', help='file(s) to parse instead of stdin', nargs='*')
_StoreAction(option_strings=[], dest='files', nargs='*', const=None, default=None, type=None, choices=None, help='file(s) to parse instead of stdin', metavar=None)
>>> parser.print_help()
usage: [-h] [files ...]
关于python - 当 nargs ='*' 时从 argparse 生成更好的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64489249/