来自文本文件的Argparse自定义帮助

Jam*_*ugh 5 python parsing arguments argparse

我想使用argparse库,因为它具有灵活性,但我无法禁用默认帮助对话框以显示文本文件中的自定义文件.我想要做的就是在传递"-h"或"--help"选项时显示文本文件中的文本.以下是我尝试此操作的示例:

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)
Run Code Online (Sandbox Code Playgroud)

但它仍然输出:

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
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

hpa*_*ulj 10

您得到的是错误信息,而不是帮助(即它不是由您生成的-h).

isip_plot_det.py: error: too few arguments
Run Code Online (Sandbox Code Playgroud)

错误消息显示正常帮助的使用部分.您可以使用usage参数更改它:

parser = ArgumentParser(usage = 'my custom usage line')
Run Code Online (Sandbox Code Playgroud)

您还可以使用测试用法显示

parser.print_usage()
Run Code Online (Sandbox Code Playgroud)

要么

astr = parser.format_usage()
Run Code Online (Sandbox Code Playgroud)

获得可打印的字符串.

普通help参数使用特殊的help动作类.它的call方法是:

def __call__(self, parser, namespace, values, option_string=None):
    parser.print_help()
    parser.exit()
Run Code Online (Sandbox Code Playgroud)

请注意,它显示帮助parser.print_help(),然后退出.只要它解析-h字符串就会发生这种情况.这样它就不会产生像too few argumentsor 那样的错误unrecognized arguments(它们在解析结束时产生).

因此,自定义帮助的另一种方法是子类化ArgumentParser,并定义自己的print_help方法.您还可以自定义exiterror方法.

默认print_help为:

def print_help(self, file=None):
    if file is None:
        file = sys.stdout
    self._print_message(self.format_help(), file)
Run Code Online (Sandbox Code Playgroud)

你可以自定义format_help.

 class MyParser(argparse.ArgumentParser):
     def format_help(self):
         return 'my custom help message\n   second line\n\n'
Run Code Online (Sandbox Code Playgroud)

样品用法:

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
...
Run Code Online (Sandbox Code Playgroud)