python學習之argparse模組的使用

來源:互聯網
上載者:User

標籤:簡單   解析命令列   字串   efault   proc   最大值   python   stand   選項參數   

以下內容主要來自:http://wiki.jikexueyuan.com/project/explore-python/Standard-Modules/argparse.htmlargparse 使用簡單樣本

我們先來看一個簡單樣本。主要有三個步驟:

  • 建立 ArgumentParser() 對象
  • 調用 add_argument() 方法添加參數
  • 使用 parse_args() 解析添加的參數

樣本:

# -*- coding: utf-8 -*-import argparseparser = argparse.ArgumentParser()parser.add_argument(‘integer‘, type=int, help=‘display an integer‘)args = parser.parse_args()print(args.integer)

 將上面的代碼儲存為檔案 argparse_usage.py,在終端運行,結果如下:

$ python argparse_usage.pyusage: argparse_usage.py [-h] integerargparse_usage.py: error: too few arguments$ python argparse_usage.py abcdusage: argparse_usage.py [-h] integerargparse_usage.py: error: argument integer: invalid int value: ‘abcd‘$ python argparse_usage.py -husage: argparse_usage.py [-h] integerpositional arguments:  integer     display an integeroptional arguments:  -h, --help  show this help message and exit$ python argparse_usage.py 1010

 

定位參數

上面的樣本,其實就展示了定位參數的使用,我們再來看一個例子 - 計算一個數的平方:

# -*- coding: utf-8 -*-import argparseparser = argparse.ArgumentParser()parser.add_argument("square", help="display a square of a given number", type=int)args = parser.parse_args()print(rgs.square**2)

 將上面的代碼儲存為檔案 argparse_usage.py,在終端運行,結果如下:

$ python argparse_usage.py 981
選擇性參數

現在看下選擇性參數的用法,所謂選擇性參數,也就是命令列參數是可選的,廢話少說,看下面例子:

# -*- coding: utf-8 -*-import argparseparser = argparse.ArgumentParser()parser.add_argument("--square", help="display a square of a given number", type=int)parser.add_argument("--cubic", help="display a cubic of a given number", type=int)args = parser.parse_args()if args.square:    print(args.square**2)if args.cubic:    print(args.cubic**3)

將上面的代碼儲存為檔案 argparse_usage.py,在終端運行,結果如下:

$ python argparse_usage.py --husage: argparse_usage.py [-h] [--square SQUARE] [--cubic CUBIC]optional arguments:  -h, --help       show this help message and exit  --square SQUARE  display a square of a given number  --cubic CUBIC    display a cubic of a given number$ python argparse_usage.py --square 864$ python argparse_usage.py --cubic 8512$ python argparse_usage.py 8usage: argparse_usage.py [-h] [--square SQUARE] [--cubic CUBIC]argparse_usage.py: error: unrecognized arguments: 8$ python argparse_usage.py  # 沒有輸出

 

混合使用

定位參數和選項參數可以混合使用,看下面一個例子,給一個整數序列,輸出它們的和或最大值(預設):

 
import argparseparser = argparse.ArgumentParser(description=‘Process some integers.‘)parser.add_argument(‘integers‘, metavar=‘N‘, type=int, nargs=‘+‘,                   help=‘an integer for the accumulator‘)parser.add_argument(‘--sum‘, dest=‘accumulate‘, action=‘store_const‘,                   const=sum, default=max,                   help=‘sum the integers (default: find the max)‘)args = parser.parse_args()print(args.accumulate(args.integers))

結果:

$ python argparse_usage.pyusage: argparse_usage.py [-h] [--sum] N [N ...]argparse_usage.py: error: too few arguments$ python argparse_usage.py 1 2 3 44$ python argparse_usage.py 1 2 3 4 --sum10

 

add_argument() 方法

add_argument() 方法定義如何解析命令列參數:

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

 

每個參數解釋如下:

  • name or flags - 選項字串的名字或者列表,例如 foo 或者 -f, --foo。
  • action - 命令列遇到參數時的動作,預設值是 store。
    • store_const,表示賦值為const;
    • append,將遇到的值儲存成列表,也就是如果參數重複則會儲存多個值;
    • append_const,將參數規範中定義的一個值儲存到一個列表;
    • count,儲存遇到的次數;此外,也可以繼承 argparse.Action 自訂參數解析;
  • nargs - 應該讀取的命令列參數個數,可以是具體的數字,或者是?號,當不指定值時對於 Positional argument 使用 default,對於 Optional argument 使用 const;或者是 * 號,表示 0 或多個參數;或者是 + 號表示 1 或多個參數。
  • const - action 和 nargs 所需要的常量值。
  • default - 不指定參數時的預設值。
  • type - 命令列參數應該被轉換成的類型。
  • choices - 參數可允許的值的一個容器。
  • required - 選擇性參數是否可以省略 (僅針對選擇性參數)。
  • help - 參數的協助資訊,當指定為 argparse.SUPPRESS 時表示不顯示該參數的協助資訊.
  • metavar - 在 usage 說明中的參數名稱,對於必選參數預設就是參數名稱,對於選擇性參數預設是全大寫的參數名稱.
  • dest - 解析後的參數名稱,預設情況下,對於選擇性參數選取最長的名稱,中劃線轉換為底線.

 

python學習之argparse模組的使用

聯繫我們

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