python命令行標準解析庫:argparse

官方Tutorial: https://docs.python.org/3/howto/argparse.html#id1

中文參考:https://www.cnblogs.com/dengtou/p/8413609.html

argparsethe recommended command-line parsing module in the Python standard library.

  • 1、定義:argparse是python標準庫裏面用來處理命令行參數的庫
  • 2、命令行參數分爲位置參數(Positional arguments可選參數(Optional arguments

        位置參數就是程序根據該參數出現的位置來確定的

[root@localhost] ls root/    #其中root/是位置參數

     可選參數是應用程序已經提前定義好的參數,不是隨意指定的,一般會加上 - 或者 --

[root@localhost] ls -l    # -l 就是ls命令裏的一個選項參數
  •  3、使用步驟:(1)import argparse    首先導入模塊

                        (2)parser = argparse.ArgumentParser()    創建一個解析對象

                        (3)parser.add_argument()    向該對象中添加你要關注的命令行參數和選項

                        (4)parser.parse_args()    進行解析

 

  • 4、 使用位置參數(Positional arguments)

先說結論,Positional arguments是必須傳入的,否則報錯

opt.py編輯: 

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo') 
args = parser.parse_args()
print(args.echo)

命令行運行:

[baiyu] python opts.py 
usage: opts.py [-h] echo
opts.py: error: the following arguments are required: echo  
''' 缺失所需參數echo, Positional arguments是必須傳入的 '''

[baiyu] python opts.py --help
usage: opts.py [-h] echo

positional arguments:  ''' 位置參數 '''
  echo

optional arguments:    ''' 可選參數,可以看到,使用argparse後,會自動生成--help '''
  -h, --help  show this help message and exit

[baiyu] python opts.py foo
foo

上面的結果看起來已經可以了,使用--help以後,顯示出了位置和選項參數,但是我們並不知道到echo是幹什麼用的,所以爲了更加細緻的操作,我們可以這樣做:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo', help='"echo the string you use here"')
args = parser.parse_args()
print(args.echo)

命令行運行:

[baiyu] python opts.py -h
usage: opts.py [-h] echo

positional arguments:
  echo        "echo the string you use here"

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

還可以進行其他操作:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
                    type = int)  # 這裏需要指定type,默認是str,否則報錯
args = parser.parse_args()
print(args.square**2)

命令行運行:

[baiyu] python opts.py 4
16

 

  • 5、使用可選參數(Optional  arguments)

先說結論:

可選參數非必須傳入,不傳入該參數,執行程序完全沒有問題(一般會設置一個默認值或爲None)

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
    print("verbosity turned on")
[baiyu] python opts.py  ''' 可不選Optional arguments '''

[baiyu] python opts.py --verbosity
usage: opts.py [-h] [--verbosity VERBOSITY]
opts.py: error: argument --verbosity: expected one argument
''' 需指定參數值 '''

[baiyu] python opts.py --verbosity 1
verbosity turned on

[baiyu] python opts.py -h
usage: opts.py [-h] [--verbosity VERBOSITY]

optional arguments:
  -h, --help            show this help message and exit
  --verbosity VERBOSITY
                        increase output verbosity

從上面的程序看到,使用--verbosity參數時,需在後面指定參數值,這裏由於沒有限制,所以可以是任何值,在不指定的時候實際上默認爲None,所以可以用if語句進行判斷操作。

但這樣並不好,應爲你的參數總是瞎傳,實際上有更好的方式去設置,比如可以設置參數類型,還有其他操作,我們舉一個設置標誌的方法:

mport argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
''' 可以看到這裏,有action="store_true", 這樣的話,使用--verbose,則爲True, 不使用則爲False,不用傳其他值進去 '''
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")
[baiyu] python opts.py                 # 不傳爲 False

[baiyu] python opts.py --verbose       # 傳爲 True
verbosity turned on

[baiyu] python opts.py --verbose 1
usage: opts.py [-h] [--verbose]
opts.py: error: unrecognized arguments: 1

[baiyu] python opts.py -h
usage: opts.py [-h] [--verbose]

optional arguments:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity

 還可以指定參數類型,指定參數值:

parser.add_argument("-v", "--verbosity", type=int,
                    help="increase output verbosity")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
  • 6、Short options

實際上我們一般用的可選參數都沒有上面那麼長,都是使用簡化後的參數,這個操作也很簡單:

parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
[baiyu] python opts.py -h
usage: opts.py [-h] [-v]

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity
  • 7、Combining Positional and Optional arguments 聯合使用兩種參數
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('squire', type=int,
                    help='display a squire of a given number')
parser.add_argument('-v', "--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
answer = args.squire ** 2
if args.verbose:
    print("the squire of {} equals {}".format(args.squire, answer))
else:
    print(answer)
[baiyu] python opts.py    ''' Positional arg必須傳入 '''
usage: opts.py [-h] [-v] squire
opts.py: error: the following arguments are required: squire

[baiyu] python opts.py 4  ''' Optional arg可選 '''
16

[baiyu] python opts.py -v 4 
the squire of 4 equals 16

[baiyu] python opts.py 4 -v   ''' 兩者順序無所謂 '''
the squire of 4 equals 16

[baiyu] python opts.py -h
usage: opts.py [-h] [-v] squire

positional arguments:
  squire         display a squire of a given number

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity
  • 8、其他一些操作
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count", default=0,
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity >= 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity >= 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)
[baiyu] python opts.py 4
16
[baiyu] python opts.py 4 -v
4^2 == 16
[baiyu] python opts.py 4 -vv
the square of 4 equals 16
[baiyu] python opts.py 4 -vvv
the square of 4 equals 16

 其他去看官網吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章