Argparse and pythonargparse in python

Source: Internet
Author: User

Argparse and pythonargparse in python

Argparse is a standard module used by python to parse command line parameters and options. It is used to replace outdated optparse modules. The argparse module is used to parse command line parameters.

 

The most basic, starting with the simplest program:

 

import argparseparser = argparse.ArgumentParser()

 

Running result:

$ python 1.py$ 

 

 

Positioning parameters:

import argparseparser=argparse.ArgumentParser()parser.add_argument("echo")parser.add_argument("hello")args = parser.parse_args()print args.ehco

Run:

$python 1.pyusage: 1.py [-h] echo hello1.py: error: too few arguments$python 1.py echousage: 1.py [-h] echo hello1.py: error: too few arguments$python 1.py echo helloecho

Methodadd_argument()To specify the command parameters required by the program;

Argparse is the default string. If it is entered as a number, an error is returned, as shown in the following code:

 

1 import argparse2 parser=argparse.ArgumentParser()3 parser.add_argument("echo", help="echo the string you use here")4 args=parser.parse_args()5 print args.echo*10

Run:

$ python 1.py 4Traceback (most recent call last):  File "1.py", line 5, in <module>    print args.square**2TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

The code must be added with type = the type you need (for example, int type is required here ):

1 import argparse2 parser=argparse.ArgumentParser()3 parser.add_argument("echo", help="echo the string you use here", type=int)4 args=parser.parse_args()5 print args.echo*10

 

 

 

-- Help:

Although the help information is already beautiful, it is not good enough. For example, we know that echo is a positioning parameter, but we do not know the meaning of this parameter. We can only guess or read the source code. Below, we can make it more helpful:

1 import argparse2 parser = argparse.ArgumentParser()3 parser.add_argument("echo", help="echo the string you use there")4 args = parser.parser_args()5 print args.echo

Run:

1 $ python 1.py -h2 usage: 1.py [-h] echo3 4 positional arguments:5   echo        echo the string you use here6 7 optional arguments:8   -h, --help  show this help message and exit

 

 

 

Reference Type:

In general, if the parameter type is not specified, argparse is of the string type by default and can be specified through type;

1 import argparse2 parser = argparse.ArgumentParser()3 parser.add_argument("square", help="display a square of a given number", type=int)4 args = parser.parse_args()5 print args.square**2

You can also use default = xx to specify the default parameter value, for example:

1 parser.add_argument("echo", action="count", default=0)

 

 

Optional parameters:

1 import argparse2 parser = argparse.ArgumentParser()3 parser.add_argument("--verbosity", help="increase output verbosity")4 args = parser.parse_args()5 if args.verbosity:6     print "verbosity turned on"

 

Run:

$ python 1.py --verbosity 1verbosity turned on$ python 1.py$ python 1.py --helpusage: prog.py [-h] [--verbosity VERBOSITY]

 

There is also an optional parameterShorthand:

1 import argparse2 parser = argparse.ArgumentParser()3 parser.add_argument("-vwww", "--verbose", help="increase output verbosity", action="store_true")4 args = parser.parse_args()5 if args.verbose:6     print "verbosity turned on"

Here, the-vww is short for it. action: store_true/store_false: Boolean switch. Store_true. The default value is False, and the input value is true. Opposite to store_flase;

1 $ python prog.py -v2 verbosity turned on3 $ python prog.py --help4 usage: prog.py [-h] [-v]5 6 optional arguments:7   -h, --help     show this help message and exit8   -v, --verbose  increase output verbosity

In the command line, if-v is the same as-vwww, an error is returned. If it is-vw, the default value is-vwww, and the value 23 is correct;

 

Note:

 

1 parser.add_argument("-v", "--verbose", action="store_true",help="increase output verbosity")

 

These are not ordered. Of course they can be the same as above;

 

 

 

Parameter conflict:

So far, we have used[argparse.ArgumentParser][6]To see another method.add_mutually_exclusive_group(). It allows us to specify a parameter that conflicts with other parameters. Next, modify the program to learn more about this new method: we will add parameters.--quiet, And parameters--verboseConflict, cannot be specified at the same time:

 1 import argparse 2 parser = argparse.ArgumentParser() 3 parser.add_argument("-v", "--verbose", type=int, help="the base") 4 parser.add_argument("-q", "--quiet", type=int, help="the exponent") 5  6 args = parser.parse_args() 7 if args.quiet: 8     print "111111" 9 elif args.verbose:10     print "222222"

Run:

1 $python 1.py -v -q2 $11111

 

 

Another methodadd_mutually_exclusive_group():

1 import argparse2 3 parser = argparse.ArgumentParser()4 group = parser.add_mutually_exclusive_group()5 group.add_argument("-v", "--verbose", action="store_true")6 group.add_argument("-q", "--quiet", action="store_true") 
7 if args.quiet:

8     print "111111"

9 elif args.verbose:

10     print "222222"

Run:

1 python 1.py -v -q2 usage: 1.py [-h] [-v | -q]3 test.py: error: argument -q/--quiet: not allowed with argument -v/--verbose

Indicates that you can use-vOr-qBut cannot be used at the same time.

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.