Python command-line arguments and getopt modules

Source: Internet
Author: User
Tags parse string

1. Source of demand

Sometimes we need to write some scripts to deal with some tasks, may enter different commands according to different conditions, to accomplish different tasks. Can you do the same thing as the Linux operating system, looking a little taller?

The answer, of course, is OK! Getopt to meet your needs.

Let's look at a system command in Linux: The ultimate goal is to write a similar script.

2.getopt Introduction

Getopt This function is used to extract the user input obtained by SYS.ARGV to determine the execution steps.

Getopt is a module, and there are getopt functions inside this module, so getopt need to do so.

getopt.getopt ([command line argument list], "Short options", [long list of options])

The function returns a value of two. OPTs and args

OPTs is a tuple that has all the options and their input values. This value cannot be modified when the input is determined.

Args is the remaining part after removing the useful input.

1 ImportGetopt,sys2Shortargs ='F:t' #短选项3Longargs = ['directory-prefix=','format','--f_long='] #长选项4opts,args= getopt.getopt (sys.argv[1:], Shortargs, Longargs)5 Print 'opts=', opts6 Print 'args=', args

" Short Options " , [long option list]) The colon after the short option name (:) indicates that the option must have additional parameters. An equal sign (=) after the long option nameindicates that the option must have additional parameters.

Several output results are:

Distinguish the data inside the Longargs long option, what must be appended to the front--, otherwise out of the ordinary. For example

Correct format:----f_long= ' data '

Error format:--f_long= ' data '

That's right:

Error:

Different data parameter formats are captured differently: OPTs is captured when the format is correct, and is captured by args when it is not a parameter format.

The wording of the option requires

For short format, the "-" sign is followed by an option letter. If there are additional parameters for this option, they can be separated by a space or separated. Any length, you can use quotation marks. The following are correct:
  -O
-oa
-obbbb
-O BBBB
-O "a B"
For long formats, the "--" sign is followed by a word. If you have additional parameters for the options, follow the "=" followed by the parameters. There must be no spaces before and after the "=" number. The following are correct:

   --help=file1

And these are not true:
--Help=file1
--help =file1
--help = File1
--help= file1

3. How to use getopt for analysis

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

1. Import the Getopt,sys module.

2. Parse command-line arguments.

3. Process the results.

First step: Import the module

Import sys,getopt

The second step: the processing method is as follows
Try :       " ho: ", ["help""output="])    Except  getopt. Getopterror:      #

The explanations are as follows:

1. The function used for processing is called getopt () because it is a getopt module that is imported directly using import, so it is possible to add a qualified getopt.
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 to parse the string "ho:". The option character is written in the parse string when an option simply represents a switch state, that is, when no additional parameters are followed. When an optional item is followed by an additional parameter, the Write option character in the parse string is appended with a ":" Number. So "ho:" means "h" is a switch option; "O:" indicates that a parameter should be followed.
4. Use the long format to parse the list of strings: ["Help", "output="]. Long format strings can also have a switch state, which is not followed by the "=" number. If you follow an equal sign, you should have a parameter later. This long format means "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 the format information for the analysis. Args is the remaining command-line argument that is not part of the format information. OPTs is a two-tuple list. Each element is: (option string, additional parameter). Empty string If no additional parameters are available.
6. The entire process uses exceptions to include, so that when parsing errors, you can print out usage information to inform the user how to use the program.

As explained above, a command line example is:
'-h-o file--help--output=out file1 file2 '
After the analysis is complete, the OPTs should be:
[('-H ', '), ('-O ', ' file '), ('--help ', '), ('--output ', ' out ')]
And the Args are:
[' File1 ', ' file2 ']

The third step: the main analysis of the parameters of the existence of the decision, and then further processing. The main processing modes are:
 for  O, a in   opts:  if  o  " -h  " ,  --help  "   if  o in  ( -o  , "  --output   ): output  = a 

Using a loop, each time a two-tuple is taken out of the opts, it is assigned to two variables. o Save the option parameter, A is an additional parameter. The option parameters are then processed.

Instance code:
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 ImportGetopt,sys4 5 defusage ():6     Print "usage:%s [-a|-o|-c] [--help|--output] args ...."%(sys.argv[0])7 8 if __name__=='__main__':9     Try:TenShortargs ='F:t' OneLongargs = ['directory-prefix=','format','--f_long='] Aopts,args= getopt.getopt (sys.argv[1:], Shortargs, Longargs) -         Print '****************opts********************' -         Print 'opts=', opts the         Print '****************args********************' -         Print 'args=', args -  -          forOpt,arginchopts: +             ifOptinch('- H','--help'): - usage () +Sys.exit (1) A             elifOptinch('--f_long'): at                 Print '--f_long=', opt -             Else: -                 Print '%s====>%s'%(Opt,arg) -     exceptgetopt. Getopterror: -         Print 'getopt error!' - usage () inSys.exit (1)

Operation Result:

[[email protected] test]# python test1.py-f ' test '-t--directory-prefix= ' aaaaaaa '----f_long= ' bbbbb '--format
opts********************
opts= [('-f ', ' Test '), ('-t ', '), ('--directory-prefix ', ' aaaaaaa '), ('----f_long ', ' bbbbb '), ('--format ', ')]
args********************
args= []
--f_long=-F
-t====>
--directory-prefix====> AAAAAAA
----F_long====> BBBBB
--format====>

Expect class hints:

[[email protected] test]# python test1.py-f ' test '-H--directory-prefix= ' aaaaaaa '----f_long= ' bbbbb '--format
Getopt error!
Usage:test1.py [-a|-o|-c] [--help|--output] args ....

Reference Document: http://andylin02.iteye.com/blog/845355

Python command-line arguments and getopt modules

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.