argparse 不能这样工作。您需要使用 -h 参数寻求帮助。否则它只会给出usage 以及错误消息。
0015:~/mypy$ python3 stack41671660.py
usage: stack41671660.py [-h] I
stack41671660.py: error: the following arguments are required: I
0015:~/mypy$ python stack41671660.py
usage: stack41671660.py [-h] I
stack41671660.py: error: too few arguments
0015:~/mypy$ python stack41671660.py -h
usage: stack41671660.py [-h] I
My Script
positional arguments:
I Provide the release log file
optional arguments:
-h, --help show this help message and exit
您可以使用nargs='?' 将位置参数设置为“可选”,并为默认值添加测试:
print(args)
if args.I is None:
parser.print_help()
样本运行:
0016:~/mypy$ python stack41671660.py
Namespace(I=None)
usage: stack41671660.py [-h] [I]
My Script
positional arguments:
I Provide the release log file
optional arguments:
-h, --help show this help message and exit
0019:~/mypy$ python stack41671660.py 2323
Namespace(I='2323')
另一种选择是自定义parser.error 方法,使其执行print_help 而不是print_usage。这将影响所有解析错误,而不仅仅是这个丢失的位置。
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
# self.print_usage(_sys.stderr)
self.print_help(_sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
`