【ZZ】getopt在Python中的使用

在運行程序時,可能須要根據不一樣的條件,輸入不一樣的命令行選項來實現不一樣的功能。目前有短選項長選項兩種格式。短選項格式爲"-"加上單個字母選項;長選項爲"--"加上一個單詞。長格式是在Linux下引入的。許多Linux程序都支持這兩種格式。在Python中提供了getopt模塊很好的實現了對這兩種用法的支持,並且使用簡單。 html


取得命令行參數
  在使用以前,首先要取得命令行參數。使用sys模塊能夠獲得命令行參數。
import sys
print sys.argv

  而後在命令行下敲入任意的參數,如:
python get.py -o t --help cmd file1 file2

  結果爲:
['get.py', '-o', 't', '--help', 'cmd', 'file1', 'file2']

  可見,全部命令行參數以空格爲分隔符,都保存在了sys.argv列表中。其中第1個爲腳本的文件名。

選項的寫法要求
  對於短格式,"-"號後面要緊跟一個選項字母。若是還有此選項的附加參數,能夠用空格分開,也能夠不分開。長度任意,能夠用引號。如如下是正確的:
-o
-oa
-obbbb
-o bbbb
-o "a b"
  對於長格式,"--"號後面要跟一個單詞。若是還有些選項的附加參數,後面要緊跟"=",再加上參數。"="號先後不能有空格。如如下是正確的:

--help=file1

  而這些是不正確的:
-- help=file1
--help =file1
--help = file1
--help= file1

如何用getopt進行分析
  使用getopt模塊分析命令行參數大致上分爲三個步驟:

1.導入getopt, sys模塊
2.分析命令行參數
3.處理結果

  第一步很簡單,只須要:
import getopt, sys

  第二步處理方法以下(以Python手冊上的例子爲例):
try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
except getopt.GetoptError:
    # print help information and exit:

1.
處理所使用的函數叫getopt(),由於是直接使用import導入的getopt模塊,因此要加上限定getopt才能夠。
2. 使用sys.argv[1:]過濾掉第一個參數(它是執行腳本的名字,不該算做參數的一部分)。
3. 使用短格式分析串"ho:"。當一個選項只是表示開關狀態時,即後面不帶附加參數時,在分析串中寫入選項字符。當選項後面是帶一個附加參數時,在分析串中寫入選項字符同時後面加一個":"號。所以"ho:"就表示"h"是一個開關選項;"o:"則表示後面應該帶一個參數。
4. 使用長格式分析串列表:["help", "output="]。長格式串也能夠有開關狀態,即後面不跟"="號。若是跟一個等號則表示後面還應有一個參數。這個長格式表示"help"是一個開關選項;"output="則表示後面應該帶一個參數。
5. 調用getopt函數。函數返回兩個列表:opts和args。opts爲分析出的格式信息。args爲不屬於格式信息的剩餘的命令行參數。opts是一個兩元組的列表。每一個元素爲:(選項串,附加參數)。若是沒有附加參數則爲空串''。
6. 整個過程使用異常來包含,這樣當分析出錯時,就能夠打印出使用信息來通知用戶如何使用這個程序。

  如上面解釋的一個命令行例子爲:
'-h -o file --help --output=out file1 file2'

  在分析完成後,opts應該是:
[('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]

  而args則爲:
['file1', 'file2']

  第三步主要是對分析出的參數進行判斷是否存在,而後再進一步處理。主要的處理模式爲:
for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    if o in ("-o", "--output"):
        output = a

  使用一個循環,每次從opts中取出一個兩元組,賦給兩個變量。o保存選項參數,a爲附加參數。接着對取出的選項參數進行處理。(例子也採用手冊的例子) python


 http://docs.python.org/2/library/getopt.html shell

15.6.getopt— C-style parser for command line options

Note less

Thegetoptmodule is a parser for command line options whose API is designed to be familiar to users of the Cgetopt()function. Users who are unfamiliar with the Cgetopt()function or who would like to write less code and get better help and error messages should consider using the argparse module instead. ide

This module helps scripts to parse the command line arguments insys.argv. It supports the same conventions as the Unixgetopt()function (including the special meanings of arguments of the form ‘-‘ and ‘--‘). Long options similar to those supported by GNU software may be used as well via an optional third argument. 函數

A more convenient, flexible, and powerful alternative is the optparse module. flex

This module provides two functions and an exception: ui

getopt.getopt( args, options [, long_options ])

Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this meanssys.argv[1:]. options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unixgetopt()uses). this

Note spa

Unlike GNUgetopt(), after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.

long_options, if specified, must be a list of strings with the names of the long options which should be supported. The leading'--'characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('='). Optional arguments are not supported. To accept only long options, options should be an empty string. Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if long_options is['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so GetoptError will be raised.

The return value consists of two elements: the first is a list of(option, value)pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of args). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g.,'-x') or two hyphens for long options (e.g.,'--long-option'), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed.

getopt.gnu_getopt( args, options [, long_options ])

This function works like getopt(), except that GNU style scanning mode is used by default. This means that option and non-option arguments may be intermixed. The getopt() function stops processing options as soon as a non-option argument is encountered.

If the first character of the option string is ‘+’, or if the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a non-option argument is encountered.

New in version 2.3.

exception getopt.GetoptError

This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none. The argument to the exception is a string indicating the cause of the error. For long options, an argument given to an option which does not require one will also cause this exception to be raised. The attributesmsgandoptgive the error message and related option; if there is no specific option to which the exception relates,optis an empty string.

Changed in version 1.6: Introduced GetoptError as a synonym for error.

exception getopt.errorAlias for GetoptError; for backward compatibility.

An example using only Unix style options:

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

Using long option names is equally easy:

>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
...     'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']

 

In a script, typical usage is something like this:

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()

 

Note that an equivalent command line interface could be produced with less code and more informative help and error messages by using the argparse module:

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output')
    parser.add_argument('-v', dest='verbose', action='store_true')
    args = parser.parse_args()
    # ... do something with args.output ...
    # ... do something with args.verbose ..
相關文章
相關標籤/搜索