您收到的是错误消息,而不是帮助(即它不是由您的-h
).
isip_plot_det.py: error: too few arguments
错误消息显示了正常帮助的用法部分。你可以用一个来改变它usage
范围:
parser = ArgumentParser(usage = 'my custom usage line')
您还可以使用以下命令测试使用情况显示
parser.print_usage()
or
astr = parser.format_usage()
获得可打印的字符串。
正常的help
参数使用特殊的help
动作类。它是call
方法是:
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
parser.exit()
请注意,它显示的帮助parser.print_help()
,然后退出。一旦它解析了,就会发生这种情况-h
细绳。这样就不会产生任何错误,例如too few arguments
or unrecognized arguments
(在解析结束时产生)。
因此,自定义帮助的另一种方法是子类化ArgumentParser
,并定义您自己的print_help
方法。您还可以自定义exit
and error
方法。
默认print_help
is:
def print_help(self, file=None):
if file is None:
file = sys.stdout
self._print_message(self.format_help(), file)
您可以定制format_help
反而。
class MyParser(argparse.ArgumentParser):
def format_help(self):
return 'my custom help message\n second line\n\n'
使用示例:
In [104]: parser=MyParser(usage='custom usage')
In [105]: parser.parse_args(['-h'])
my custom help message
second line
...
In [106]: parser.parse_args(['unknown'])
usage: custom usage
ipython3: error: unrecognized arguments: unknown
...