欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中最好用的命令行參數(shù)解析工具(argparse)

 更新時間:2019年08月23日 09:31:06   作者:Python編程時光  
這篇文章主要介紹了Python中最好用的命令行參數(shù)解析工具(argparse),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

Python 做為一個腳本語言,可以很方便地寫各種工具。當(dāng)你在服務(wù)端要運(yùn)行一個工具或服務(wù)時,輸入?yún)?shù)似乎是一種硬需(當(dāng)然你也可以通過配置文件來實(shí)現(xiàn))。

如果要以命令行執(zhí)行,那你需要解析一個命令行參數(shù)解析的模塊來幫你做這個苦力活。

Python 本身就提供了三個命令行參數(shù)解析模塊,我這里羅列一下它們的大致情況供你了解。

  • getopt,只能簡單的處理命令行參數(shù)
  • optparse,功能強(qiáng)大,易于使用,可以方便地生成標(biāo)準(zhǔn)的、符合Unix/Posix 規(guī)范的命令行說明。
  • argparse,使其更加容易的編寫用戶友好的命令行接口。它所需的程序進(jìn)程了參數(shù)定義,argparse將更好的解析sys.argv。同時argparse模塊還能自動生成幫助及用戶輸入錯誤參數(shù)時的提示信息。

很多初學(xué)者可能會使用getopt,上手簡單功能也簡單。比如說optget無法解析一個參數(shù)多個值的情況,如 --file file1 file2 file3,而 optparse 實(shí)際上我沒有用過,但是考慮到它在Python2.7后就已經(jīng)棄用不再維護(hù),我們通常也不會使用它。

接下來只剩下 argparse 這一神器,它幾乎能滿足我對命令解析器的所有需求。它支持解析一參數(shù)多值,可以自動生成help命令和幫助文檔,支持子解析器,支持限制參數(shù)取值范圍等等功能。

0. HelloWorld

不管學(xué)習(xí)什么東西,首先第一步都應(yīng)該是掌握它的大體框架。

而 使用 argparse 前,框架很簡單,你只需要記住這三行。

# mytest.py
import argparse
parser = argparse.ArgumentParser(description="used for test")

args = parser.parse_args()

現(xiàn)在可以嘗試一下

[root@localhost ~]# python mytest.py -h
usage: mytest.py [-h]

used for test

optional arguments:
 -h, --help show this help message and exit
[root@localhost ~]# 
[root@localhost ~]# 
[root@localhost ~]# python mytest.py
[root@localhost ~]# 

已經(jīng)可以使用了。

1. 入門配置

這里先講一下,比較常用的參數(shù)配置。

  • 調(diào)試:debug
  • 版本號:version
import argparse
parser = argparse.ArgumentParser()

parser.add_argument('--version', '-v', action='version',
          version='%(prog)s version : v 0.01', help='show the version')

parser.add_argument('--debug', '-d', action='store_true',
          help='show the version',
          default=False)

args = parser.parse_args()
print("=== end ===")

上面debug處的配置,需要講一下的是 action='store_true' 和 default = False 的作用和區(qū)別

  • store_true:一旦指定了 -d 或者 --debug ,其值就為 True,store_false則相反
  • default=False:未指定 -d 或者 --debug,其值就默認(rèn)為False

當(dāng)我們執(zhí)行 python mytest.py -v,就會打印 version 里的內(nèi)容。

[root@localhost ~]# python mytest.py -v
mytest.py version : v 0.01
[root@localhost ~]# 

一旦執(zhí)行時,指定了參數(shù) -v ,執(zhí)行到 parser.parse_args() 就會退出程序,不會打印最后的 === end ===

2. 參數(shù)種類

參數(shù)可分為 必選參數(shù)(positional arguments) 和 可選參數(shù)(optional arguments)。

在argsparse 里如何實(shí)現(xiàn)呢?

必選參數(shù)

用單詞做參數(shù),默認(rèn)就為必選參數(shù)

# mytest.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("name")

args = parser.parse_args()

print(args.name)

不指定name參數(shù)運(yùn)行一下:python mytest.py

[root@localhost ~]# python mytest.py 
usage: mytest.py [-h] name
mytest.py: error: too few arguments
[root@localhost ~]#

如預(yù)期一樣,報(bào)錯了,說缺少參數(shù)。那我們指定一下:python mytest.py name wangbm

[root@localhost ~]# python mytest.py wangbm
wangbm
[root@localhost ~]# 

可選參數(shù)

有兩種方式:

  • 單下劃線 - 來指定的短參數(shù),如-h;
  • 雙下劃線 -- 來指定的長參數(shù),如--help
# mytest.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbosity", help="increase output verbosity")

args = parser.parse_args()

if args.verbosity:
 print("verbosity turned on")
else:
  print("verbosity turned off")

試著運(yùn)行一下 python mytest.py,不會報(bào)錯。

[root@localhost ~]# python mytest.py
verbosity turned off
[root@localhost ~]#

3. 參數(shù)類型

有的參數(shù),是字符串,有的參數(shù),是數(shù)值。

為了對命令行中的參數(shù)進(jìn)行有效的約束,我們可以事先對參數(shù)的類型進(jìn)行聲明。argparse 會對參數(shù)進(jìn)行校驗(yàn),不通過時,會直接拋出錯誤。

# mytest.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("age", type=int)

args = parser.parse_args()

print(args.name)
print(args.age)

測試一下唄。

[root@localhost ~]# python mytest.py wangbm eighteen
usage: mytest.py [-h] name age
mytest.py: error: argument age: invalid int value: 'eighteen'
[root@localhost ~]# 
[root@localhost ~]# python mytest.py wangbm 18
wangbm
18
[root@localhost ~]#

你看,寫 eighteen 就不行,提示類型不合法,只有寫 18 才行。

4. 互斥參數(shù)

有些參數(shù),是互斥的,有你無我。比如,性別。

在 argparse 中如何實(shí)現(xiàn)?

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-m", "--male", action="store_true")
group.add_argument("-f", "--female", action="store_true")
args = parser.parse_args()

如果同時指定了這兩個參數(shù),就會報(bào)錯。

[root@localhost ~]# python mytest.py -f
[root@localhost ~]# python mytest.py -m
[root@localhost ~]# python mytest.py -m -f 
usage: mytest.py [-h] [-m | -f]
mytest.py: error: argument -f/--female: not allowed with argument -m/--male
[root@localhost ~]# 

5. 可選值

如果是性別,可以像上面那樣放在兩個參數(shù)里然后用互斥組來約束,也可以放在一個參數(shù)里,在argparse里限制再在外層做判斷。

# mytest.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-g", "--gender", default='male',
          choices=['male', 'female'])

args = parser.parse_args()
print(args.gender)

試著執(zhí)行一下,發(fā)現(xiàn)性別只能是男或女,不能為人妖。

[root@localhost ~]# python mytest.py --gender male
male
[root@localhost ~]# python mytest.py --gender female
female
[root@localhost ~]# 
[root@localhost ~]# 
[root@localhost ~]# python mytest.py --gender other
usage: mytest.py [-h] [-g {male,female}]
mytest.py: error: argument -g/--gender: invalid choice: 'other' (choose from 'male', 'female')
[root@localhost ~]#

6. 指定文件

經(jīng)常會有那種要在腳本中指定配置文件或者其他文件的需求。可以使用下面的配置

import argparse
parser = argparse.ArgumentParser()

parser.add_argument('--file', '-f', action='append',
          dest='files',
          help=('additional yaml configuration files to use'),
          type=argparse.FileType('rb'))
          
args = parser.parse_args()

dest=files,是說將命令行中,--file 的參數(shù)值賦值給變量files,你可以用args.files訪問。

action=append,由于我們會有指定多個文件的需求,那就指定多次--file ,argparse會將其放在一個list里。

type=argparse.FileType('rb'),既然是指定文件,那么參數(shù)應(yīng)該為路徑,并指定打開模式為rb,如果如果要取得文件內(nèi)容,可以用 args.files[0].read()

7. 子解析器

如果你對命令行,有過足夠多的接觸,就會知道有些情況下會有子解析器。

這里我以自己工作中,碰到的例子來舉個例子。

cloud-init --debug single -name mymodule

其中 single 后面是一個子解析器。

# cloud-init.py

def main_single(name, args):
  print("name: ", name)
  print("args: ", args)
  print("I am main_single")

# 添加一個子解析器
subparsers = parser.add_subparsers()

parser_single = subparsers.add_parser('single',help='run a single module')

# 對single 子解析器添加 action 函數(shù)。
parser_single.set_defaults(action=('single', main_single))

# require=True,是說如果命令行指定了single解析器,就必須帶上 --name 的參數(shù)。
parser_single.add_argument("--name", '-n', action="store",
              help="module name to run",
              required=True)

args = parser.parse_args()

(name, functor) = args.action
if name in ["single"]:
  functor(name, args)

執(zhí)行命令cloud-init single -name mymodule,輸出如下

name:  single
args:  Namespace(action=('single', <function main_single at 0x0000000003F161E0>), debug=False, file=None, name='mymodule')
I am main_single

以上就是關(guān)于 argparse 工具的使用方法,你學(xué)會了嗎?希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python編寫彈球游戲的實(shí)現(xiàn)代碼

    python編寫彈球游戲的實(shí)現(xiàn)代碼

    這篇文章主要介紹了python編寫彈球游戲的實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2018-03-03
  • 使用pytorch讀取數(shù)據(jù)集

    使用pytorch讀取數(shù)據(jù)集

    這篇文章主要介紹了使用pytorch讀取數(shù)據(jù)集,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • python的中異常處理機(jī)制

    python的中異常處理機(jī)制

    這篇文章主要介紹了python的中異常處理的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • python多進(jìn)程并發(fā)的實(shí)現(xiàn)示例

    python多進(jìn)程并發(fā)的實(shí)現(xiàn)示例

    python中的多線程無法利用多核優(yōu)勢,如果想要充分地使用多核CPU的資源,在python中大部分情況需要使用多進(jìn)程,本文主要介紹了python多進(jìn)程并發(fā)的實(shí)現(xiàn)示例,感興趣的可以了解一下
    2024-02-02
  • Python裝飾器有哪些絕妙的用法

    Python裝飾器有哪些絕妙的用法

    本文主要介紹了Python裝飾器有哪些絕妙的用法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • Python retrying 重試機(jī)制的使用方法

    Python retrying 重試機(jī)制的使用方法

    我們在程序開發(fā)中,經(jīng)常會需要請求一些外部的接口資源,而且我們不能保證每次請求一定會成功,所以這些涉及到網(wǎng)絡(luò)請求的代碼片段就需要加上重試機(jī)制。本文就來詳細(xì)的介紹一下,感興趣的可以了解一下
    2021-09-09
  • python3.6中anaconda安裝sklearn踩坑實(shí)錄

    python3.6中anaconda安裝sklearn踩坑實(shí)錄

    這篇文章主要介紹了python3.6中anaconda安裝sklearn踩坑實(shí)錄,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • Python對接支付寶支付自實(shí)現(xiàn)功能

    Python對接支付寶支付自實(shí)現(xiàn)功能

    這篇文章主要介紹了Python對接支付寶支付自實(shí)現(xiàn)功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-10-10
  • python模擬事件觸發(fā)機(jī)制詳解

    python模擬事件觸發(fā)機(jī)制詳解

    這篇文章主要為大家詳細(xì)介紹了python模擬事件觸發(fā)機(jī)制的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Python tkinter實(shí)現(xiàn)春節(jié)煙花效果demo

    Python tkinter實(shí)現(xiàn)春節(jié)煙花效果demo

    這篇文章主要為大家介紹了Python實(shí)現(xiàn)春節(jié)煙花效果demo,本文為大家提供了兩種實(shí)現(xiàn)方式代碼,詳細(xì)的實(shí)現(xiàn)一場浪漫的煙花秀,有需要的朋友可以借鑒參考下
    2024-01-01

最新評論