免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
getopt在Python中的使用(轉(zhuǎn))

在運(yùn)行程序時(shí),可能需要根據(jù)不同的條件,輸入不同的命令行選項(xiàng)來實(shí)現(xiàn)不同的功能。目前有短選項(xiàng)長選項(xiàng)兩種格式。短選項(xiàng)格式為"-"加上單個(gè)字母選項(xiàng);長選項(xiàng)為"--"加上一個(gè)單詞。長格式是在Linux下引入的。許多Linux程序都支持這兩種格式。在Python中提供了getopt模塊很好的實(shí)現(xià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)的寫法要求
  對于短格式,"-"號后面要緊跟一個(gè)選項(xiàng)字母。如果還有此選項(xiàng)的附加參數(shù),可以用空格分開,也可以不分開。長度任意,可以用引號。如以下是正確的:
-o
-oa
-obbbb
-o bbbb
-o "a b"
  對于長格式,"--"號后面要跟一個(gè)單詞。如果還有些選項(xiàng)的附加參數(shù),后面要緊跟"=",再加上參數(shù)。"="號前后不能有空格。如以下是正確的:

--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é)果

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

  第二步處理方法如下(以Python手冊上的例子為例):
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:]過濾掉第一個(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è)":"號。所以"ho:"就表示"h"是一個(gè)開關(guān)選項(xiàng);"o:"則表示后面應(yīng)該帶一個(gè)參數(shù)。
4. 使用長格式分析串列表:["help","output="]。長格式串也可以有開關(guān)狀態(tài),即后面不跟"="號。如果跟一個(gè)等號則表示后面還應(yīng)有一個(gè)參數(shù)。這個(gè)長格式表示"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è)過程使用異常來包含,這樣當(dāng)分析出錯(cuò)時(shí),就可以打印出使用信息來通知用戶如何使用這個(gè)程序。

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

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

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

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

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


 

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

Note

The getopt module is a parser for command lineoptions whose API is designed to be familiar to users of the Cgetopt() function. Users who are unfamiliar withthe C getopt() function or who would like to write lesscode and get better help and error messages should consider usingthe argparse module instead.

This module helps scripts to parse the command line arguments insys.argv. It supports the same conventions as theUnix getopt() function (including the special meaningsof arguments of the form ‘-‘ and ‘--‘). Long options similar to those supported byGNU software may be used as well via an optional thirdargument.

A more convenient, flexible, and powerful alternative is theoptparse module.

This module provides two functions and an exception:

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

Parses command line options and parameter list. args isthe argument list to be parsed, without the leading reference tothe running program. Typically, this means sys.argv[1:].options is the string of option letters that the scriptwants to recognize, with options that require an argument followedby a colon (':'; i.e., the same format that Unix getopt()uses).

Note

Unlike GNU getopt(),after a non-option argument, all further arguments are consideredalso non-options. This is similar to the way non-GNU Unix systemswork.

long_options, if specified, must be a list of stringswith the names of the long options which should be supported. Theleading '--' characters should not be included in theoption name. Long options which require an argument should befollowed by an equal sign ('='). Optionalarguments are not supported. To accept only long options,options should be an empty string. Long options on thecommand line can be recognized so long as they provide a prefix ofthe option name that matches exactly one of the accepted options.For example, if long_options is ['foo', 'frob'], the option --fowill 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 listof (option,value) pairs; the second is the listof program arguments left after the option list was stripped (thisis a trailing slice of args). Each option-and-value pairreturned has the option as its first element, prefixed with ahyphen for short options (e.g., '-x') or twohyphens for long options (e.g., '--long-option'),and the option argument as its second element, or an empty stringif the option has no argument. The options occur in the list in thesame order in which they were found, thus allowing multipleoccurrences. 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 meansthat option and non-option arguments may be intermixed. Thegetopt() function stops processing options assoon as a non-option argument is encountered.

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

New inversion 2.3.

exceptiongetopt.GetoptError

This is raised when an unrecognized option is found in theargument list or when an option requiring an argument is givennone. The argument to the exception is a string indicating thecause of the error. For long options, an argument given to anoption which does not require one will also cause this exception tobe raised. The attributes msg andoptgive the error message and related option; if there is no specificoption to which the exception relates, opt is anempty string.

Changed inversion 1.6: Introduced GetoptError as a synonym for error.

exceptiongetopt.error
Alias 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, 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 producedwith less code and more informative help and error messages byusing 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 ..
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
python命令行參數(shù)是什么
getopt()和getopt_long()函數(shù)參數(shù)分析
getopt(),optind
Linux環(huán)境(一)--程序參數(shù)
Linux下getopt()函數(shù)的簡單使用
Python 命令行參數(shù) | 菜鳥教程
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服