Python命令行參數解析模塊argparse

前言

更多內容,請訪問個人 我的博客python


之前 optparse 比較火,可是在python2.7版本後,官方再也不維護這個模塊,轉而大力支持 argparsebash

argparse 模塊可讓人輕鬆編寫用戶友好的命令行接口。她能夠從 sys.argv 中解析出參數,並自動生成幫助和使用手冊,還能在傳入無效參數時報出錯誤信息。app

基礎用法

因爲是標準庫,因此不須要安裝,直接使用:python2.7

import argparse
parser = argparse.ArgumentParser()
# parser.add_argument("-i", "--info", action = "store", type = "string", dest = "sample_info", help = "the sample information")
args = parser.parse_args()
# print(args.sample_info)
複製代碼

運行以上代碼,以下:ui

  • 不輸入參數,也沒有輸出結果:
    $ python3 test.py
    複製代碼
  • 輸入默認參數 --help (也可縮寫爲 -h ),會輸出自動生成的幫助信息:
    $ python3 test.py --help
    
    # 輸出:
    usage: test.py [-h]
    
    optional arguments:
      -h, --help  show this help message and exit
    複製代碼
  • 輸入錯誤參數,會輸出報錯信息:
    $ python3 test.py -verbose
    
    # 輸出:
    usage: test.py [-h]
    test.py: error: unrecognized arguments: --verbose
    複製代碼

建立解析器

使用 argparse 的第一步是建立一個 ArgumentParser 對象,以下:this

import argparse

parser = argparse.ArgumentParser(prog=None, usage=None,description=None, 
epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, 
argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)
複製代碼

建立一個新的 ArgumentParser 對象。全部的參數都應看成爲關鍵字參數傳入。部分參數在下面都有它更詳細的描述,但簡而言之,它們是:spa

  • prog - 程序的名稱(默認:sys.argv[0])
  • usage - 描述程序用途的字符串(默認值:從添加到解析器的參數生成)
  • description - 在參數幫助文檔以前顯示的文本(默認值:無)
  • epilog - 在參數幫助文檔以後顯示的文本(默認值:無)
  • parents - 一個 ArgumentParser 對象的列表,它們的參數也應包含在內
  • formatter_class - 用於自定義幫助文檔輸出格式的類
  • prefix_chars - 可選參數的前綴字符集合(默認值:'-')
  • fromfile_prefix_chars - 當須要從文件中讀取其餘參數時,用於標識文件名的前綴字符集合(默認值:None)
  • argument_default - 參數的全局默認值(默認值: None)
  • conflict_handler - 解決衝突選項的策略(一般是沒必要要的)
  • add_help - 爲解析器添加一個 -h/--help 選項(默認值: True)
  • allow_abbrev - 若是縮寫是無歧義的,則容許縮寫長選項 (默認值:True)
prog

默認狀況下, ArgumentParser 對象在幫助消息中顯示的程序名稱是 sys.argv[0] 。若要自定義程序名,則使用 prog ,以下:命令行

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.print_help()
usage: myprogram [-h]

optional arguments:
 -h, --help  show this help message and exit
複製代碼

不管是從 sys.argv[0] 或是從 prog= 參數肯定的程序名稱,均可以在幫助消息裏經過 %(prog)s 格式串來引用,以下:code

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.add_argument('--foo', help='foo of the %(prog)s program')
>>> parser.print_help()
usage: myprogram [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo of the myprogram program
複製代碼
usage

構建用法消息,以下:orm

>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [options]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help
複製代碼
description

簡要描述這個程度作什麼以及怎麼作。在幫助消息中,這個描述會顯示在命令行用法字符串和各類參數的幫助消息之間,以下:

>>> parser = argparse.ArgumentParser(description='A foo that bars')
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit
複製代碼
epilog

一些程序喜歡在 description 參數後顯示額外的對程序的描述,以下:

>>> parser = argparse.ArgumentParser(
...     description='A foo that bars',
...     epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit

And that's how you'd foo a bar
複製代碼
add_help

是否關閉自動生成的幫助信息,以下:

>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]

optional arguments:
 --foo FOO  foo help
複製代碼

添加參數

使用 add_argument() 方法添加參數。其中,部分參數在下面都有它更詳細的描述,但簡而言之,它們是:

  • name or flags - 一個命名或者一個選項字符串的列表,例如 foo 或 -f, --foo。
  • action - 當參數在命令行中出現時使用的動做基本類型。
  • nargs - 命令行參數應當消耗的數目。
  • const - 被一些 action 和 nargs 選擇所需求的常數。
  • default - 當參數未在命令行中出現時使用的值。
  • type - 命令行參數應當被轉換成的類型。
  • choices - 可用的參數的容器。
  • required - 此命令行選項是否可省略 (僅選項可用)。
  • help - 一個此選項做用的簡單描述。
  • metavar - 在使用方法消息中使用的參數值示例。
  • dest - 被添加到 parse_args() 所返回對象上的屬性名。
name or flags

第一個傳遞給 add_argument() 的參數必須是一系列 flags 或者是一個簡單的參數名,以下:

>>> parser.add_argument('-f', '--foo')

or

>>> parser.add_argument('bar')
複製代碼
action
  • store - 存儲參數的值。這是默認的動做。以下:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args('--foo 1'.split())
Namespace(foo='1')
複製代碼
  • store_const - 存儲被 const 命名參數指定的值。 store_const 動做一般用在選項中來指定一些標誌。以下:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
Namespace(foo=42)
複製代碼
  • store_truestore_false - 這些是 store_const 分別用做存儲 TrueFalse 值的特殊用例。另外,它們的默認值分別爲 FalseTrue。以下:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)
複製代碼
  • append - 存儲一個列表,而且將每一個參數值追加到列表中。在容許屢次使用選項時頗有用。以下:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])
複製代碼
  • count - 計算一個關鍵字參數出現的數目或次數。例如,對於一個增加的詳情等級來講有用。以下:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count')
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)
複製代碼
  • version - 指望有一個 version= 命名參數在 add_argument() 調用中,並打印版本信息並在調用後退出。以下:
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
>>> parser.parse_args(['--version'])
PROG 2.0
複製代碼
相關文章
相關標籤/搜索