来自文本文件的 Argparse 自定义帮助 [英] Argparse custom help from text file
问题描述
我想使用 argparse 库,因为它具有灵活性,但我无法禁用默认帮助对话框以显示文本文件中的自定义帮助对话框.我想要做的就是在传递-h"或--help"选项时显示文本文件中的文本.这是我如何尝试此操作的示例:
I want to use the argparse library because of its flexibility, but I am having trouble disabling the default help dialogue to show a custom one from a text file. All I want to do is display the text from the text file when the "-h" or "--help" option is passed. Here is an example of how I am trying this:
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("file", type=str, nargs='+')
parser.add_argument("-xmin", type=float)
parser.add_argument("-xmax", type=float)
parser.add_argument("-ymin", type=float)
parser.add_argument("-ymax", type=float)
parser.add_argument("-h", "--help", action="store_true")
args = parser.parse_args()
if args.help is True:
print isip_get_help()
exit(-1)
但它仍然输出:
nedc_[1]: python isip_plot_det.py -h
usage: isip_plot_det.py [-xmin XMIN] [-xmax XMAX] [-ymin YMIN] [-ymax YMAX]
[-h]
file [file ...]
isip_plot_det.py: error: too few arguments
有什么想法吗?
推荐答案
您得到的是错误消息,而不是帮助(即它不是由您的 -h
生成的).
What you are getting is an error message, not the help (i.e. it's not produced by your -h
).
isip_plot_det.py: error: too few arguments
错误信息显示了正常帮助的使用部分.您可以使用 usage
参数更改它:
The error message shows the usage part of the normal help. You can change that with a usage
parameter:
parser = ArgumentParser(usage = 'my custom usage line')
您还可以使用
parser.print_usage()
或
astr = parser.format_usage()
获取可打印的字符串.
普通的help
参数使用一个特殊的help
动作类.它的call
方法是:
The normal help
argument uses a special help
action class. Its call
method is:
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
parser.exit()
请注意,它使用 parser.print_help()
显示帮助,然后退出.一旦解析 -h
字符串,就会发生这种情况.这样它就不会产生任何错误,例如参数太少
或无法识别的参数
(在解析结束时产生).
Notice that it displays the help with parser.print_help()
, and then exits. That occurs as soon as it parses the -h
string. That way it doesn't produce any errors like the too few arguments
or unrecognized arguments
(which are produced at the end of parsing).
因此自定义帮助的另一种方法是子类化 ArgumentParser
,并定义您自己的 print_help
方法.您还可以自定义 exit
和 error
方法.
So another way of customizing the help is to subclass ArgumentParser
, and define your own print_help
method. You can also customize the exit
and error
methods.
默认的print_help
是:
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
...
这篇关于来自文本文件的 Argparse 自定义帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!