python 命令列參數解析

來源:互聯網
上載者:User

標籤:position   incr   numbers   attribute   lin   協助資訊   rip   val   transform   

本文是從我還有一個部落格轉載過來的,歡迎大家點擊進去看一下,幫我添加點人氣^_^ImPyy
選擇模組

依據python參考手冊的提示,optparse 已經廢棄,應使用 argparse

教程概念

argparse 模組使用 add_argument 來加入可選的命令列參數,原型例如以下:

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:    name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.     action - The basic type of action to be taken when this argument is encountered at the command line.     nargs - The number of command-line arguments that should be consumed.     const - A constant value required by some action and nargs selections.     default - The value produced if the argument is absent from the command line.     type - The type to which the command-line argument should be converted.     choices - A container of the allowable values for the argument.     required - Whether or not the command-line option may be omitted (optionals only).     help - A brief description of what the argument does.     metavar - A name for the argument in usage messages.     dest - The name of the attribute to be added to the object returned by parse_args(). 

上面的說明事實上不用看,直接看示範範例好了:

只想展示一些資訊
# -*- coding: utf-8 -*-"""argparse tester"""import argparseparser = argparse.ArgumentParser(description=‘argparse tester‘)parser.add_argument("-v", "--verbose", help="increase output verbosity",                    action="store_true")args = parser.parse_args()if args.verbose:    print "hello world"


它會輸出例如以下:

$ python t.py$ python t.py -vhello world$ python t.py -husage: t.py [-h] [-v]argparse testeroptional arguments:  -h, --help     show this help message and exit  -v, --verbose  increase output verbosity

這裡 -v 是這個選項的簡寫。--verbose 是完整拼法,都是能夠的

help 是協助資訊。不解釋了

args = parse_args() 會返回一個命名空間,僅僅要你加入了一個可選項,比方 verbose。它就會把 verbose 加到 args 裡去,就能夠直接通過 args.verbose 訪問。

假設你想給它起個別名,就須要在 add_argument 裡加多一個參數 dest=‘vb‘

這樣你就能夠通過 args.vb 來訪問它了。

action="store_true" 表示該選項不須要接收參數,直接設定 args.verbose = True,

當然假設你不指定 -v。那麼 args.verbose 就是 False

但假設你把 action="store_true" 去掉,你就必須給 -v 指定一個值。比方 -v 1

做個求和程式
# -*- coding: utf-8 -*-"""argparse tester"""import argparseparser = argparse.ArgumentParser(description=‘argparse tester‘)parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")parser.add_argument(‘numbers‘, type=int, help="numbers to calculate", nargs=‘+‘)parser.add_argument(‘-s‘, ‘--sum‘, help="sum all numbers", action=‘store_true‘, default=True)args = parser.parse_args()print "Input:", args.numbersprint "Result:"results = args.numbersif args.verbose:    print "hello world"if args.sum:    results = sum(args.numbers)    print "tSum:tt%s" % results

輸出例如以下:

[[email protected] test]$ python t2.py -husage: t2.py [-h] [-v] [-s] numbers [numbers ...]argparse testerpositional arguments:  numbers        numbers to calculateoptional arguments:  -h, --help     show this help message and exit  -v, --verbose  increase output verbosity  -s, --sum      sum all numbers[[email protected] test]$ python t2.py 1 2 3 -sInput: [1, 2, 3]Result:    Sum:        6

注意到這此可選項 numbers 不再加上 “-” 首碼了。由於這個是位置選項

假設把 nargs="+" 去掉,則僅僅能輸入一個數字。由於它指定了number 選項的值個數

假設把 type=int 去掉。則 args.numbers 就是一個字串。而不會自己主動轉換為整數

注意到 --sum 選項的最後還加上了 default=True。意思是即使你不在命令列中指定 -s,它也會預設被設定為 True

僅僅能2選1的可選項
# -*- coding: utf-8 -*-"""argparse tester"""import argparseparser = argparse.ArgumentParser(description=‘argparse tester‘)#group = parser.add_mutually_exclusive_group()parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")parser.add_argument(‘numbers‘, type=int, help="numbers to calculate", nargs=‘+‘)parser.add_argument(‘-s‘, ‘--sum‘, help="sum all numbers", action=‘store_true‘, default=True)parser.add_argument(‘-f‘, ‘--format‘, choices=[‘int‘, ‘float‘], help=‘choose result format‘, default=‘int‘)args = parser.parse_args()print "Input:", args.numbersprint "Result:"results = args.numbersif args.verbose:    print "hello world"if args.format == ‘int‘:    format = ‘%d‘else:    format = ‘%f‘if args.sum:    results = sum(args.numbers)    print ‘tsum:tt%s‘ % (format % results)

輸出例如以下:

[[email protected] test]$ python t2.py 1 2 3 -f floatInput: [1, 2, 3]Result:    sum:        6.000000[[email protected] test]$ python t2.py 1 2 3 -f doubleusage: t2.py [-h] [-v] [-s] [-f {int,float}] numbers [numbers ...]t2.py: error: argument -f/--format: invalid choice: ‘double‘ (choose from ‘int‘, ‘float‘)

在加入選項 -f 時,傳入了 choices=[‘int‘, ‘float‘] 參數。表示該選項僅僅能從 int 或 float 中2選1

python 命令列參數解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.