日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

getopt在Python中的使用

發(fā)布時(shí)間:2023/12/2 python 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 getopt在Python中的使用 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

在運(yùn)行程序時(shí),可能需要根據(jù)不同的條件,輸入不同的命令行選項(xiàng)來(lái)實(shí)現(xiàn)不同的功能。目前有短選項(xiàng)長(zhǎng)選項(xiàng)兩種格式。短選項(xiàng)格式為"-"加上單個(gè)字母選項(xiàng);長(zhǎng)選項(xiàng)為"--"加上一個(gè)單詞。長(zhǎng)格式是在Linux下引入的。許多Linux程序都支持這兩種格式。在Python中提供了getopt模塊很好的實(shí)現(xiàn)了對(duì)這兩種用法的支持,而且使用簡(jiǎn)單。


取得命令行參數(shù)
  在使用之前,首先要取得命令行參數(shù)。使用sys模塊可以得到命令行參數(shù)。
import sys
print sys.argv

  然后在命令行下敲入任意的參數(shù),如:
python get.py -o t --help cmd file1 file2

  結(jié)果為:
['get.py', '-o', 't', '--help', 'cmd', 'file1', 'file2']

  可見,所有命令行參數(shù)以空格為分隔符,都保存在了sys.argv列表中。其中第1個(gè)為腳本的文件名。

選項(xiàng)的寫法要求
  對(duì)于短格式,"-"號(hào)后面要緊跟一個(gè)選項(xiàng)字母。如果還有此選項(xiàng)的附加參數(shù),可以用空格分開,也可以不分開。長(zhǎng)度任意,可以用引號(hào)。如以下是正確的:
-o
-oa
-obbbb
-o bbbb
-o "a b"
  對(duì)于長(zhǎng)格式,"--"號(hào)后面要跟一個(gè)單詞。如果還有些選項(xiàng)的附加參數(shù),后面要緊跟"=",再加上參數(shù)。"="號(hào)前后不能有空格。如以下是正確的:

--help=file1

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

如何用getopt進(jìn)行分析
  使用getopt模塊分析命令行參數(shù)大體上分為三個(gè)步驟:

1.導(dǎo)入getopt, sys模塊
2.分析命令行參數(shù)
3.處理結(jié)果

  第一步很簡(jiǎn)單,只需要:
import getopt, sys

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

1.
?處理所使用的函數(shù)叫getopt(),因?yàn)槭侵苯邮褂胕mport導(dǎo)入的getopt模塊,所以要加上限定getopt才可以。
2.?使用sys.argv[1:]過(guò)濾掉第一個(gè)參數(shù)(它是執(zhí)行腳本的名字,不應(yīng)算作參數(shù)的一部分)。
3.?使用短格式分析串"ho:"。當(dāng)一個(gè)選項(xiàng)只是表示開關(guān)狀態(tài)時(shí),即后面不帶附加參數(shù)時(shí),在分析串中寫入選項(xiàng)字符。當(dāng)選項(xiàng)后面是帶一個(gè)附加參數(shù)時(shí),在分析串中寫入選項(xiàng)字符同時(shí)后面加一個(gè)":"號(hào)。所以"ho:"就表示"h"是一個(gè)開關(guān)選項(xiàng);"o:"則表示后面應(yīng)該帶一個(gè)參數(shù)。
4.?使用長(zhǎng)格式分析串列表:["help", "output="]。長(zhǎng)格式串也可以有開關(guān)狀態(tài),即后面不跟"="號(hào)。如果跟一個(gè)等號(hào)則表示后面還應(yīng)有一個(gè)參數(shù)。這個(gè)長(zhǎng)格式表示"help"是一個(gè)開關(guān)選項(xiàng);"output="則表示后面應(yīng)該帶一個(gè)參數(shù)。
5.?調(diào)用getopt函數(shù)。函數(shù)返回兩個(gè)列表:opts和args。opts為分析出的格式信息。args為不屬于格式信息的剩余的命令行參數(shù)。opts是一個(gè)兩元組的列表。每個(gè)元素為:(選項(xiàng)串,附加參數(shù))。如果沒有附加參數(shù)則為空串''。
6.?整個(gè)過(guò)程使用異常來(lái)包含,這樣當(dāng)分析出錯(cuò)時(shí),就可以打印出使用信息來(lái)通知用戶如何使用這個(gè)程序。

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

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

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

  第三步主要是對(duì)分析出的參數(shù)進(jìn)行判斷是否存在,然后再進(jìn)一步處理。主要的處理模式為:
for o, a in opts:
????if o in ("-h", "--help"):
????????usage()
????????sys.exit()
????if o in ("-o", "--output"):
????????output = a

  使用一個(gè)循環(huán),每次從opts中取出一個(gè)兩元組,賦給兩個(gè)變量。o保存選項(xiàng)參數(shù),a為附加參數(shù)。接著對(duì)取出的選項(xiàng)參數(shù)進(jìn)行處理。(例子也采用手冊(cè)的例子)


?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.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, 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 ..

?

總結(jié)

以上是生活随笔為你收集整理的getopt在Python中的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。