The Argparse in Python

Source: Internet
Author: User

Argparse is a standard module used by Python to parse command-line arguments and options in place of obsolete optparse modules. The role of the Argparse module is used to parse command-line arguments.

The most basic, starting from one of the simplest programs:

Import= argparse. Argumentparser ()

Operation Result:

 

Positioning parameters:

Import argparseparser=argparse. Argumentparser () parser.add_argument ("echo") parser.add_argument ("  Hello"= Parser.parse_args ()print Args.ehco

Run:

11echo  Hello11echo1  echo  Hello11echo   Hello  Echo

Method add_argument() To specify the command parameters that the program needs to accept;

And Argparse is the default string, if entered as a numeric error, as shown in the following code:

1 Import Argparse 2 parser=argparse. Argumentparser ()3 parser.add_argument ("echo", help="  echo the string,"here")4 args=Parser.parse_args ()5  Print args.echo*10

Run:

1 4  last):  '1.py'5 in <module>     Print args.square** 2for'str' ' int '

The code must be added type= the type you need (like this requires an int type):

1 Import Argparse 2 parser=argparse. Argumentparser ()3 parser.add_argument ("echo", help="Echo The string "Here", type=int)4 args=Parser.parse_args ()  5Print args.echo*10

--help:

Although the help information is now very beautiful, but not good enough. For example, we know that ECHO is a positional parameter, but we don't know the meaning of the parameter, only by guessing or reading the source code. Below, we can make it more helpful:

1 Import Argparse 2 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] Echo34positional Arguments:5  echo        echo the stringyou use here67Optional Arguments:8   -H,--help and   exit

Reference type:

In general, if you do not specify a parameter type, Argparse defaults to the string type, which can be specified by type;

1 Import Argparse 2 parser = Argparse. Argumentparser ()3 parser.add_argument ("square", help="  Display a square of a givennumber", type=int)4 args = Parser.parse_args () 
    5print args.square**2

You can also use DEFAULT=XX to specify values for default parameters, such as:

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

Optional Parameters:

1 ImportArgparse2Parser =Argparse. Argumentparser ()3Parser.add_argument ("--verbosity", help="Increase output verbosity")4args =Parser.parse_args ()5 ifargs.verbosity:6     Print "verbosity turned on"

Run:

1 1  11. PY--helpusage:prog.py [-h] [--verbosity verbosity]

There is also a shorthand for optional parameters:

1 ImportArgparse2Parser =Argparse. Argumentparser ()3Parser.add_argument ("-vwww","--verbose", help="Increase output verbosity", action="store_true")4args =Parser.parse_args ()5 ifArgs.verbose:6     Print "verbosity turned on"

Here the-VWW is its shorthand, Action:store_true/store_false: boolean switch. Store_true. The default is false, and the input is true. Store_flase opposite;

1 $ python prog.py-v2verbosity turnedon3 $ python prog.py – Help 4 usage:prog.py [-h] [-v]56Optional arguments:7   -H, --help show this help     message and exit8   -V,--verbose  increase output verbosity

In the command line as long as the-vwww before the same line, if the-VP will be error, if it is-VW, the default is-vwww, also a 23 is correct;

Attention:

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

These are not sequential, of course, it can be the same as above;

Parameter conflict:

So far, we've used [argparse.ArgumentParser][6] two methods to look at one of his other methods add_mutually_exclusive_group() . It allows us to specify a parameter and other parameter conflicts. The following procedure modifies the following program to learn more about this new method: We will add the parameter --quiet , it conflicts with the parameter --verbose , cannot specify simultaneously:

1 ImportArgparse2Parser =Argparse. Argumentparser ()3Parser.add_argument ("- v","--verbose", Type=int, help="The base")4Parser.add_argument ("- Q","--quiet", Type=int, help="The exponent")5 6args =Parser.parse_args ()7 ifArgs.quiet:8     Print "111111"9 elifArgs.verbose:Ten     Print "222222"

Run:

1 1. py-v-Q2 $11111

Another methodadd_mutually_exclusive_group():

1 ImportArgparse2 3Parser =Argparse. Argumentparser ()4Group =Parser.add_mutually_exclusive_group ()5Group.add_argument ("- v","--verbose", action="store_true")6Group.add_argument ("- Q","--quiet", action="store_true")
7 if args.quiet:

8 Print "111111"

9 elif args.verbose:

Print "222222"

Run:

1 1. py-v-Q21. py [-h] [-v |-Q]3 test.py:error:argument-q/-- Quiet:not allowed with Argument-v/--verbose

Indicates that it can be used -v or -q , but not used at the same time.

The Argparse in Python

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.