Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print program usage example with argparse module

I am trying to learn how to use python's argparse module. Currently my python script is:

parser = argparse.ArgumentParser(description='My first argparse attempt',                                 add_help=True) parser.add_argument("-q", action ="store", dest='argument',                     help="First argument") output = parser.parse_args() 

And it gives the output as :

usage: test.py [-h] [-q ARGUMENT]  My first argparse attempt  optional arguments:   -h, --help   show this help message and exit   -q ARGUMENT  First argument 

Now, lets suppose I want my -h or --help argument to print a usage example also. Like,

   Usage: python test.py -q "First Argument for test.py" 

My purpose is to print the above usage example along with the default content of -h argument so that the user can get a basic idea of how to use the test.py python script.

So, is this functionality inbuilt in the argparse module. If no than what is the correct way to approach this problem.

like image 404
RanRag Avatar asked Jun 07 '12 11:06

RanRag


People also ask

What does Argparse return?

Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

What does Argparse ArgumentParser () do?

ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required .


1 Answers

Use parser.epilog to display something after the generated -h text.

parser = argparse.ArgumentParser(     description='My first argparse attempt',     epilog='Example of use')  output = parser.parse_args() 

prints:

My first argparse attempt  optional arguments:   -h, --help  show this help message and exit  Example of use 
like image 56
georg Avatar answered Sep 20 '22 20:09

georg