() Function used in Python getopt

When you run the program, you may need based on different conditions, different input command line options to achieve different functions. There are two options for short options and long format. Short format options "-" plus a single-letter options; long options "-" plus a word. Long format was introduced in Linux. Many Linux programs support both formats. In Python provides a good getopt module implements these two usage support, and easy to use.


Command-line arguments made
  before use, you must first get command line arguments. Sys module may use command line parameters.
SYS Import
Print the sys.argv

  then typing any command line parameters, such as:
Python get.py cmd file1 file2 -ot --help

  results:
[ 'get.py', '-o', 'T', '--help', 'cmd', 'file1', 'file2']

  can be seen, all command line arguments as a space separator, are stored in the sys.argv list. The first of a script file name.

Options written request
  for the short format, "-" behind the numbers to keep up with an option letter. If there are additional parameters for this option can be separated by a space, it can not be separated. Any length, can be quoted. As is correct:
-o
-OA
-obbbb
-o bbbb
-o "A B"
  to the long format, "-" followed by a number to keep word. If you have some additional parameter options, the back to keep up with "=", together with the parameters. "=" No spaces before and after the number.

As is correct: --help = file1

  which are incorrect:
- Help = file1
--help = file1
--help = file1
--help = file1

how getopt analysis
  using getopt module analyzes the command line parameters generally divided into three steps:

1. Import getopt, sys module
2. Analysis of command line parameters
3. the processing result

, for example, module test1.py:
Import getopt, sys

the opts, args = getopt.getopt (the sys.argv [. 1:], "HO:", [ " help "," output = "] ) #" ho: " may be written as '-HO:'
Print (the opts)

print (args)

function used in a process called 1. getopt (), because it is directly introduced getopt import module, so to add only be defined getopt.
2. Use sys.argv [1:] filter out the first argument (which is the name of the script execution, should not be counted as part of the argument).
3. Analysis using the short format string "ho:". When an option is only that switch state, i.e. when the back with no additional parameters in the analysis writes option character string. When the option is followed with an additional parameter, writes option character string in the analysis back while adding a ":" Number. Therefore, "ho:" says "h" is a switching option; "o:" indicates that a parameter should take back.
4. Analysis using the long form sequence listing: [ "help", "output ="]. Long format string may be a switching state, i.e. not followed by "=" sign. If followed by an equal sign it said back there should be a parameter. This long format "help" is a switching option; "output =" indicates that a parameter should take back.
5. Call getopt function. The function returns two lists: opts and args. opts for the format of information to analyze. args not for the remaining command-line parameters of the format information, i.e. not in accordance with the outside () long or short option character which defines additional parameters and information getopt . opts is a list of a two-tuples. Each element is a string :( option, additional parameters). If no additional parameter null string '' .
6. The whole process to include the use of an exception, so when analyzing the error, you can print out using the information to inform the user how to use this program.

A command line with the above-explained operation example:

python test1.py '-h -o file --help --output = out file1 file2'

output opts as:
[( '-H', ''), ( '-o', 'File'), ( '--help', ''), ( '--output', 'out')]

and compared args: [ 'file1', 'file2 '], which is above the rest of the command line format information does not belong to the parameters .

For the above example, add the following code, the main parameter is analyzed to judge whether or not there, and then further processed. The main processing mode is:
for O, A in the opts:
    IF O in ( "-H", "--help"):
        Usage ()
        the sys.exit ()
    IF O in ( "-o", "--output "):
        Output = a

 use of a loop, each taken from a two-tuple opts in two variables assigned. o save option parameters, a as additional parameters. Next, the extraction processing option parameters.

Transfer from: http: //blog.csdn.net/q_l_s/article/details/52921675

Here then attached a better explanation of the link to the article: http: //www.jianshu.com/p/a877e5b46b2d

You can use the following code to run it, enter a different command-line parameters to test, document test2.py:

Copy the code
 1 import getopt
 2 import sys
 3 
 4 opts,args = getopt.getopt(sys.argv[1:],'-h-f:-v',['help','filename=','version'])
 5 print(opts)
 6 for opt_name,opt_value in opts:
 7     if opt_name in ('-h','--help'):
 8         print("[*] Help info")
 9         sys.exit()
10     if opt_name in ('-v','--version'):
11         print("[*] Version is 0.01 ")
12         sys.exit()
13     if opt_name in ('-f','--filename'):
14         fileName = opt_value
15         print("[*] Filename is ",fileName)
16         # do something
17         sys.exit()
Copy the code

I ipython console input Spyder inside:

% run sys_test2.py -f test
Output: [( '- F', 'Test')]
[*] Test IS Filename

Try it yourself other inputs to see the function.

Guess you like

Origin www.cnblogs.com/zhf123/p/11610017.html