The getopt of Python

Source: Internet
Author: User
Tags parse string

Getopt can parse input parameters and enter different commands according to different parameters.

getopt.getopt ([command line argument list], "Short options", "Long option List")

Getopt This function, is used to extract sys.argv to obtain user input to determine the subsequent operation of the

Getopt is a module, and this module has a getopt function,

function returns 2 values of OPTs and args
OPTs is a tuple that holds all the options and their input values, and when the input is determined, the value cannot be changed.
Args is the remaining part after removing the useful input
#!/usr/bin/env python2.6# coding:utf-8import getoptimport sys shortargs = ' f:t ' #短选项longargs = [' Nocolor ', ' format ', '--f _long ', '---f_longlong= ']opts, argv = Getopt.getopt (sys.argv[1:], Shortargs, Longargs) opts = Dict (opts) print Optsprint a rgv

1 The colon after the short option name: Indicates that the option must have additional parameters such as-f fir; If no colon is added, arguments are not placed in args, such as-t long

2 long options inside the data, need to precede the--, otherwise reported abnormal; there is an equal sign stating that there are parameters, such as--format (correct)--format=1 (error)

The wording of the option

for short options. After the "-" is followed by an option letter, if this option has additional parameters, can be separated by a space, or can not be separated, length arbitrary, you can use quotation marks, the following is the correct

-O

-oa

-obbbb

-O "a B"

For the long option, "--" followed by a word, if there are additional parameters of this option, followed by "=", plus parameters, note that "=" can not have spaces before and after, the following is the correct wording

--help=man

Incorrect wording

--Help=file

--help =file

--help = File

--help= file

How to use getopt for analysis

Using the Getopt module to analyze command-line parameters is broadly divided into three steps

1 Importing the Getopt,sys module

2 Parsing command-line arguments

3 processing Results

#!/usr/bin/env python2.6# coding:utf-8import getopt,systry:    opts, args = Getopt.getopt (sys.argv[1:], "ho:", ["Help "," output= "]) except getopt. Getopterror:    # Print help information and exit:    print ' ERROR '    sys.exit (0) print Optsprint args

1 the function used for processing is getopt, because it is the Getopt module imported directly from the import, so it is possible to add a qualified getopt

2 Use Sys.argv[1:] 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 option to analyze the string "ho:" When the first option is simply to represent a switch state, followed by an additional parameter, after parsing the string write option character, when the selected item is accompanied by an additional parameter, the Write option character in the parse string is appended with a ":" Number, so "ho:", which means "H" is a switch option, "O:" indicates that a parameter should be followed

4 using the long option to analyze the list of strings: ["Help", "output="], long option string also has a switch state, that is, after the "=" number, if followed by a "=" sign that there should be a parameter, the long format means "help" is an option switch; "output=" Indicates that a parameter should be followed with the

5 Call the Getopt function, the function returns two lists, opts and args,opts for the parsed format information, args for the remaining command-line arguments that are not part of the format information, opts is a two-tuple list, each element is (option string, additional parameter), if there is no additional parameter is empty string

A chestnut

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

After the analysis is complete, the OPTs should be:

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

and args is:

[' File1 ', ' file2 ']

The following is the analysis of the parameters to determine the existence, and then do the next process,

For O, a in opts:    if O in ("-H", "--help"):        #usage () #处理函数        sys.exit ()    if o in ("-O", "--output"):        # Processing function        Sys.exit ()

Using a loop, each time a two-tuple is taken out of the OPTs, assigned to two variables, O save the option parameter, A is an additional parameter, determine whether there is, near one step processing

Full code:

#!/usr/bin/env python2.6# coding:utf-8import getopt, sys def usage ():    print "usage:%s [-a|-o|-c] [--help|--output ] args ... "% (sys.argv[0]) if __name__ = = ' __main__ ':    try:        Shortargs = ' f:t '        Longargs = [' directory-prefix= ', ' format ', '--f_long= ']        opts, args = Getopt.getopt (sys.argv[1:], Shortargs, Longargs)        print ' *************** opts********************** '        print ' opts= ', opts        print ' ***********************args*************** '        print ' args= ', args        for opt, arg in opts:            if-opt in  ('-H ', '--help '):                usage ()                sys. Exit (1)            elif opt in ('--f_long '):                print '--f_long= ', opt             else:                print '%s==========>%s '% (OPT, a RG)    except getopt. Getopterror:        print ' getopt error '        usage ()        sys.exit (1)

 

Execution results


Reference Document: Https://www.cnblogs.com/chushiyaoyue/p/5380022.html

The getopt of Python

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.