不能這樣工作。您需要向-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_usage
而不是print_help
。這將影響所有的解析錯誤,而不僅僅是這個缺失的位置。
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)
`