Use of getopt in Python

Source: Internet
Author: User
Tags element groups
Author: limodou

When running a program, you may need to enter different command line options based on different conditions to implement different functions. Currently, there are two formats: short option and long option. The short option format is "-" with a single letter option; the long option is "--" with a word. The long format is introduced in Linux. Many Linux programs support these two formats. The getopt module is provided in Python to support the two usage methods. It is easy to use and I will introduce its usage to you.

Obtain command line parameters

You must obtain the command line parameters before using them. Use the SYS module to obtain command line parameters.

Import sys
Print sys. argv

Then, input any parameters in the command line, such:

Python get. py-o t -- help cmd file1 file2

Result:

['Get. py', '-O', 't',' -- help', 'cmd', 'file1', 'file2']

It can be seen that all command line parameters are saved in the SYS. argv list with space as the separator. Among them, 1st are the script file names.

Option writing requirements

For short formats, the "-" must be followed by an option letter. If you have additional parameters for this option, you can separate them with spaces or not. Any length. You can use quotation marks. Which of the following is true:

-O
-Oa
-Obbbb
-O BBBB
-O "a B"

For long format, "--" is followed by a word. If there are additional parameters for some options, they must be followed by "=", followed by parameters. No space is allowed before and after "=. Which of the following is true:

-- Help = file1

These are incorrect:

-- Help = file1
-- Help = file1
-- Help = file1
-- Help = file1

How to Use getopt for analysis

Using the getopt module to analyze command line parameters involves three steps:

1. Import the getopt and SYS modules.
2. Analyze command line parameters
3. processing result

The first step is simple, as long:

Import getopt, sys

That's all.

The second step is somewhat complicated. Use the example in the python manual to describe it:

Try:
Opts, argS = getopt. getopt (SYS. argv [1:], "Ho:", ["help", "output ="])
Counter t getopt. getopterror:
# Print help information and exit:

1. The function used for processing is getopt (). Because it is the getopt module imported directly using import, you must add the getopt limitation.
2. Use SYS. argv [1:] to filter out the first parameter (it is the name of the execution script and should not be counted as part of the parameter ).
3. Use the short format analysis string "Ho :". When an option only indicates the switch status, that is, when no additional parameter is provided, the option character is written into the analysis string. When the option is followed by an additional parameter, write the option character in the analysis string and add. Therefore, "Ho:" indicates that "H" is a switch option; "O:" indicates that a parameter should be followed.
4. Use the long format to analyze the string list: ["help", "output ="]. Long format strings can also be in the switch status, that is, they are not followed by the "=" sign. If there is an equal sign, it indicates that there should be a parameter later. This long format indicates that "help" is a switch option; "output =" indicates that a parameter should be followed.
5. Call the getopt function. The function returns two lists: opts and args. Opts is the analyzed format information. ARGs is the remaining command line parameter that does not belong to the format information. Opts is a list of two-element groups. Each element is: (option string, additional parameter ). If no parameter is attached, it is an empty string ''.
6. The entire process contains exceptions. In this way, when an analysis error occurs, you can print the usage information to notify you how to use the program.

Explain what is an option and what is a parameter.
1). A single character, indicating options,
2). A single character followed by a colon: indicates that this option must be followed by a parameter. Parameters are immediately followed by options or separated by spaces. The pointer of this parameter is assigned to optarg.
3). A single character is followed by two colons, indicating that this option must be followed by a parameter. Parameters must be followed by no space. The pointer of this parameter is assigned to optarg. (This feature is the expansion of GNU ).

As explained above, the command line example is:

'-H-o file -- help -- output = out file1 file2'

After the analysis is complete, opts should be:

[('-H', ''), ('-O', 'file'), ('-- help',''), (' -- output ', 'out')]

While ARGs is:

['File1', 'file2']

Step 3 is also relatively simple. In this step, we mainly determine whether the analysis parameters exist and then process them further. The main processing mode is:

For O, a in opts:
If O in ("-h", "-- Help "):
Usage ()
SYS. Exit ()
If O in ("-o", "-- output "):
Output =

Use a loop to retrieve a two-element group from opts each time and assign two variables. O save option parameter. A is an additional parameter. Then, process the retrieved option parameters. (Manual examples are also used)

Postscript

For complete program examples, refer to the python manual. It is really easy to implement the getopt function in Python. This technology is also used in my htmlcombine Program (Multiple HTML file merging programs. If you are interested, take a look.

Copyright limodou (chatme@263.net) If You Want To reprint please keep this information!

---------------------------
Python beckoned http://pyrecord.126.com to you

From: http://www.linuxforum.net/forum/showthreaded.php? Cat = & board = Python & number = 131459 & page = 0 & view = collapsed & SB = 5 & O = all

Related Article

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.