Argparse special help from a text file

I want to use the argparse library because of its flexibility, but I am unable to disable the default help dialog to show user text from a text file. All I want to do is display the text from a text file when the option "-h" or "--help" is passed. Here is an example of how I do 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)

But he still outputs:

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

Any ideas?

+4
source share
2 answers

What you get is an error message, not help (i.e. it is not created by yours -h).

isip_plot_det.py: error: too few arguments

. usage:

parser = ArgumentParser(usage = 'my custom usage line')

parser.print_usage()

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 unrecognized arguments ( ).

, ArgumentParser print_help. exit error.

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
...
+6

file. , action , , , i, e, args.help ​​ True. , , sys.exit - , , , ( ) ( , , -h file, ).

parser.register ( , API, - argparse.py, , ) , , ArgumentParser print_help isip_get_help().

- :

class MyArgumentParser(argparse.ArgumentParser):

    def print_help(self, file=None):
        print(isip_get_help())
        exit(-1)

parser = MyArgumentParser()
...

add_help, print_help .

+1

Source: https://habr.com/ru/post/1617351/


All Articles