Python之命令解析模組optparse

來源:互聯網
上載者:User

標籤:python   命令解析   optparse   

樣本

from optparse import OptionParser[...]def main():    usage = "usage: %prog [options] arg"    parser = OptionParser(usage)    parser.add_option("-f", "--file", dest="filename",                      help="read data from FILENAME")    parser.add_option("-v", "--verbose",                      action="store_true", dest="verbose")    parser.add_option("-q", "--quiet",                      action="store_false", dest="verbose")    [...]    (options, args) = parser.parse_args()    if len(args) != 1:        parser.error("incorrect number of arguments")    if options.verbose:        print "reading %s..." % options.filename    [...]if __name__ == "__main__":    main()
增加選項(add_option())
OptionParser.add_option(option)OptionParser.add_option(*opt_str, attr=value, ...)

定義短選項
parser.add_option(“-f”, attr=value, …)

定義長選項
parser.add_option(“–foo”, attr=value, …)

如果定義

?parser.add_option("-f", "--file", action="store", type="string", dest="filename")

命令列格式可以有以下形式

-ffoo-f foo--file=foo--file foo

解析後結果
options.filename = “foo”

解析(parse_args())

(options, args) = parser.parse_args()

options 解析後的參數,以字典形式儲存
args 不能解析的參數,以列表形式儲存

行為(action)
  • store 預設行為,儲存值到dest

  • “store_const” 儲存常量

  • “append” append this option’s argument to a list

  • “count” increment a counter by one

  • “callback” call a specified function

設定預設值(default)
parser.add_option("-v", action="store_true", dest="verbose", default=True)parser.set_defaults(verbose=True)
產生協助提示(help)

提供help選項即可,可以用parser.print_help()列印出來
parser.add_option(“-f”, “–file”, dest=”filename”,help=”write report to FILE”, metavar=”FILE”)

設定boolean值

支援store_true和store_false兩個行為

parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose")

如果遇到-v,verbose=True;如果遇到-q,verbose=False

錯誤處理
(options, args) = parser.parse_args()[...]if options.a and options.b:    parser.error("options -a and -b are mutually exclusive")
選項組(Grouping Options)

格式如下
class optparse.OptionGroup(parser, title, description=None)

group = OptionGroup(parser, "Dangerous Options",                    "Caution: use these options at your own risk.  "                    "It is believed that some of them bite.")group.add_option("-g", action="store_true", help="Group option.")parser.add_option_group(group)

提示結果如下

Usage: <yourscript> [options] arg1 arg2Options:  -h, --help            show this help message and exit  -v, --verbose         make lots of noise [default]  -q, --quiet           be vewwy quiet (I‘m hunting wabbits)  -f FILE, --filename=FILE                        write output to FILE  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or                        expert [default: intermediate]  Dangerous Options:    Caution: use these options at your own risk.  It is believed that some    of them bite.    -g                  Group option.

Python之命令解析模組optparse

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.