Detailed description of the Python command-line parsing tool argparse usage

Source: Internet
Author: User
This article is mainly for you to explain the Python command-line parsing tool argparse usage, interested in small partners can refer to

Recently in the study of Pathon's command-line parsing tool, Argparse, which is the recommended tool for writing command-line programs in the Python standard library.

Used to do UI programs, today tried the command-line program, feel pretty good, do not spend a lot of time to study the interface problems, especially in VC + + is particularly cumbersome.

Now using Python to implement the command line, the core compute module can be used to write the extension library, the effect is very good.

Learn Argparse, in the official documents found an article toturial, simple translation of the next.

Http://docs.python.org/2/howto/argparse.html#id1

Argparse Tutorial
This tutorial provides a concise introduction to the use of the command-line parameter resolution module--argparse recommended by the Python standard library.

1. Basic Concepts

In this tutorial we demonstrate the functionality of argparse with a common ls command.

$ lscpython devguide prog.py pypy rm-unused-function.patch$ ls pypyctypes_configure demo dotviewer include Lib_pypy lib-py Thon $ ls-ltotal 20drwxr-xr-x wena wena 4096 Feb 18:51 cpythondrwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide-r Wxr-xr-x 1 wena wena 535 Feb 00:05 prog.pydrwxr-xr-x + wena wena 4096 Feb 7 00:59 pypy-rw-r--r--1 wena wena 741 Feb 1 8 01:01 rm-unused-function.patch$ ls--helpusage:ls [OPTION] ... [FILE] ... List information about the FILEs (the current directory by default). Sort entries Alphabetically if none Of-cftuvsux nor--sort is specified.

From the above four commands, we are able to understand the following basic concepts:

1), ls command can be run without parameters, the default print out all the contents of the current directory.
2), if we want it to show more, then we need to give it a little more parameters. In this case, we want to display a different directory, pypy. What we have done is to identify common positional parameters (positional argument), which is named because the program needs to decide what to do based on the position of the parameter on the command line. This concept is closer to the command CP, which uses CP src DEST,SRC to represent the file you want to copy, and Dest indicates where you want to copy the file.
3), now, I want to change the behavior of the program. In our case, I want to show the westward information of the file, not just the file name, and the parameter-L is the optional parameter we know (optinal argument)
4), the last sentence is a fragment of the document that displays help, and you can learn how to use it when you encounter a command that you have never used.

2. Basic understanding

We start with a basic program (it doesn't do anything)

Import Argparseparser = Argparse. Argumentparser () Parser.parse_args ()

Operation Result:

$ python prog.py$ python prog.py--helpusage:prog.py [-h]optional arguments:-H,--help show this help message and exit$ Python prog.py--verboseusage:prog.py [-h]prog.py:error:unrecognized arguments:--verbose$ python prog.py Foousage:pro g.py [-h]prog.py:error:unrecognized Arguments:foo

Results Analysis:

1), if you do not give parameters to run this program, will not get any results.
2), the second name shows the benefits of using the Argparse, you did nothing, but got a good help information.
3), we do not need to set the--help parameters, you can get a good help information. But giving other parameters (such as Foo) produces an error.

3. Position parameters

First, give an example:

Import Argparseparser = Argparse. Argumentparser () parser.add_argument ("echo") args = Parser.parse_args () print Args.echo

Operation Result:

$ Python prog.pyusage:prog.py [-h] echoprog.py:error:the following arguments is required:echo$ python prog.py--helpu sage:prog.py [-h] echopositional arguments:echooptional arguments:-H,--help show this help message and exit$ python PR og.py Foofoo

Results Analysis:

This time, we have added a add_argument () method to set the command-line arguments that the program can accept.
Now to run the program, you must set a parameter.
The Parse_args () method actually returns some data from our command-line arguments, which in the example above is the Echo
This process, like "magic", is done automatically by Argparse.
Although the auto-generated help information is beautifully presented, it is still not possible to know exactly what it is doing based on the echo parameter. So, we've added something that makes it more useful.

Import Argparseparser = Argparse. Argumentparser () parser.add_argument ("echo", help= "echo the String,") args = Parser.parse_args () print Args.echo

Operation Result:

$ Python prog.py-husage:prog.py [-h] echopositional Arguments:echo echo the string you use    hereoptional arguments: -H,--help show this help message and exit

On that basis, let's change a little bit more: (Calculate square of the input parameter square)

Import Argparseparser = Argparse. Argumentparser () parser.add_argument ("Square", help= "display a square of a given number") args = Parser.parse_args () print Args.square**2

Here is the result of the operation:

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

This program does not work correctly because Argparse will treat the input as a string, so we need to set its type: (Type=int)

Import Argparseparser = Argparse. Argumentparser () parser.add_argument ("Square", help= "display a square of a given number",          type=int) args = Parser.parse_args () Print args.square**2

Here is the result of the operation:

$ python prog.py 416$ python prog.py fourusage:prog.py [-h] squareprog.py:error:argument square:invalid int value: ' fo ur

Now, the program runs smoothly and can handle some of the wrong inputs.

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.