Use getopt in Python

Source: Internet
Author: User
Tags element groups

 

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 "-" plus a single letter.
The length option adds a word. The long format is introduced in Linux. Many Linux programs support these two formats. The getopt module is provided in Python.
Now we support these two usage methods, and they are easy to use.

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 leading or trailing spaces are allowed. Which of the following is true:

-Help = file1

These are incorrect:

-- help=file1
--help =file1
--help = file1
--help= file1

(Note: According to my tests, it seems that I can use-help file1 directly .)

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 very simple. You only need:

Import getopt, sys

The second step is as follows (taking the example in the python Manual as an example ):

try:
opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
except 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
Add a ":" to the character of the write option. 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.

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']

The third step is to determine whether the analysis parameters exist before further processing. The main processing mode is:

for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-o", "--output"):
output = a

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.

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.