Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom 'usage' function in argparse?

Is it possible to add a custom 'usage' function instead of default usage message provided by python argparse.

Sample code:

parser = argparse.ArgumentParser(description='Sample argparse py')
parser.add_argument('-arg_1',type=int, custom_usage_funct('with_some_message'))
output = parser.parse_args()

def custom_usage_funct(str):
    print str
    print '''
       Usage: program.py
         [-a, Pass argument a]
         [-b, Pass argument b]
         [-c, Pass argument c]
         [-d, Pass argument d]
         comment
         more comment
        '''

If the argument passed is a string value as instead of integer then the program should call a custom usage function with a error message "Please provide an integer value"

Valid argument

program.py -arg_1 123

Invalid argument

program.py -arg_1 abc

       Please provide an integer value
       Usage: program.py
         [-a, Pass argument a]
         [-b, Pass argument b]
         [-c, Pass argument c]
         [-d, Pass argument d]
         comment
         more comment
like image 824
devav2 Avatar asked Jan 17 '14 12:01

devav2


People also ask

What is ArgumentParser ()?

argparse — parse the arguments. Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user. That user might be your future self.

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What does Argparse ArgumentParser () do?

>>> parser = argparse. ArgumentParser(description='Process some integers. ') The ArgumentParser object will hold all the information necessary to parse the command line into Python data types.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.


2 Answers

Yes, The default message can be overridden with the usage= keyword argument like this,

def msg(name=None):                                                            
    return '''program.py
         [-a, Pass argument a]
         [-b, Pass argument b]
         [-c, Pass argument c]
         [-d, Pass argument d]
         comment
         more comment
        '''

and using

import argparse
parser = argparse.ArgumentParser(description='Sample argparse py', usage=msg())
parser.add_argument("-arg_1", help='with_some_message')
parser.print_help()

the above output is like this,

usage: program.py
         [-a, Pass argument a]
         [-b, Pass argument b]
         [-c, Pass argument c]
         [-d, Pass argument d]
         comment
         more comment


Sample argparse py

optional arguments:
  -h, --help    show this help message and exit
  -arg_1 ARG_1  with_some_message

Note: Refer here

You can also call a custom function based on argument input using action= keyword argument:

>>> class FooAction(argparse.Action):
...     def __call__(self, parser, namespace, values, option_string=None):
...         print '%r %r %r' % (namespace, values, option_string)
...         setattr(namespace, self.dest, values)
...
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=FooAction)
>>> parser.add_argument('bar', action=FooAction)
>>> args = parser.parse_args('1 --foo 2'.split())
Namespace(bar=None, foo=None) '1' None
Namespace(bar='1', foo=None) '2' '--foo'
>>> args
Namespace(bar='1', foo='2')
like image 188
Syed Habib M Avatar answered Sep 26 '22 22:09

Syed Habib M


Yes, use the usage option. From the docs:

>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [options]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help
like image 32
aquavitae Avatar answered Sep 23 '22 22:09

aquavitae