getopt在Python中的使用
在運行程序時,可能需要根據不同的條件,輸入不同的命令行選項來實現不同的功能。目前有短選項和長選項兩種格式。短選項格式為"-"加上單個字母選項;長選項為"--"加上一個單詞。長格式是在Linux下引入的。許多Linux程序都支持這兩種格式。在Python中提供了getopt模塊很好的實現了對這兩種用法的支持,而且使用簡單。
取得命令行參數
在使用之前,首先要取得命令行參數。使用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為附加參數。接著對取出的選項參數進行處理。(例子也采用手冊的例子)
?http://docs.python.org/2/library/getopt.html
15.6.getopt— C-style parser for command line options
Note
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.
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.
This module provides two functions and an exception:
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).
Note
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_optionsis['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.GetoptErrorThis 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, sysdef 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 = Noneverbose = Falsefor o, a in opts:if o == "-v":verbose = Trueelif o in ("-h", "--help"):usage()sys.exit()elif o in ("-o", "--output"):output = aelse: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 argparseif __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 ..?
總結
以上是生活随笔為你收集整理的getopt在Python中的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 获取系统相关编码的函数
- 下一篇: 便利的开发工具-log4cpp快速使用指