當前位置:
首頁 > 知識 > 使用 Python 解析參數

使用 Python 解析參數

使用 Python 解析參數


使用 argparse 模塊像專業人士一樣解析參數。

-- Seth Kenlon(作者)

如果你在使用 Python 進行開發,你可能會在終端中使用命令,即使只是為了啟動 Python 腳本或使用 pip 安裝 Python 模塊。命令可能簡單而單一:

$ ls

命令也可能需要參數:

$ ls example

命令也可以有選項或標誌:

$ ls --color example

有時選項也有參數:

$ sudo firewall-cmd --list-all --zone home

參數

POSIX shell 會自動將你輸入的內容作為命令分成數組。例如,這是一個簡單的命令:

$ ls example

命令 ls 的位置是 $0,參數 example 位置是 $1。

可以寫一個循環迭代每項。確定它是否是命令、選項還是參數。並據此採取行動。幸運的是,已經有一個名為 argparse 的模塊。


argparse

argparse 模塊很容易集成到 Python 程序中,並有多種便利功能。例如,如果你的用戶更改選項的順序或使用一個不帶參數的選項(稱為布爾,意味著選項可以打開或關閉設置),然後另一個需要參數(例如 --color red),argparse 可以處理多種情況。如果你的用戶忘記了所需的選項,那麼 argparse 模塊可以提供友好的錯誤消息。

要在應用中使用 argparse,首先要定義為用戶提供的選項。你可以接受幾種不同的參數,而語法一致又簡單。

這是一個簡單的例子:

#!/usr/bin/env python
import argparse
import sys
def getOptions(args=sys.argv[1:]):
parser = argparse.ArgumentParser(description="Parses command.")
parser.add_argument("-i", "--input", help="Your input file.")
parser.add_argument("-o", "--output", help="Your destination output file.")
parser.add_argument("-n", "--number", type=int, help="A number.")
parser.add_argument("-v", "--verbose",dest="verbose",action="store_true", help="Verbose mode.")
options = parser.parse_args(args)
return options

此示例代碼創建一個名為 getOptions 的函數,並告訴 Python 查看每個可能的參數,前面有一些可識別的字元串(例如 --input 或者 -i)。 Python 找到的任何選項都將作為 options 對象從函數中返回(options 是一個任意名稱,且沒有特殊含義。它只是一個包含函數已解析的所有參數的摘要的數據對象)。

默認情況下,Python 將用戶給出的任何參數視為字元串。如果需要提取整數(數字),則必須指定選項 type=int,如示例代碼中的 --number 選項。

如果你有一個只是關閉和打開功能的參數,那麼你必須使用 boolean 類型,就像示例代碼中的 --verbose 標誌一樣。這種選項只保存 True 或 False,用戶用來指定是否使用標誌。如果使用該選項,那麼會激活 stored_true。

當 getOptions 函數運行時,你就可以使用 options 對象的內容,並讓程序根據用戶調用命令的方式做出決定。你可以使用測試列印語句查看 options 的內容。將其添加到示例文件的底部:

print(getOptions())

然後帶上參數運行代碼:

$ python3 ./example.py -i foo -n 4
Namespace(input="foo", number=4, output=None, verbose=False)

檢索值

示例代碼中的 options 對象包含了用戶提供的選項後面的值(或派生的布爾值)。例如,在示例代碼中,可以通過 options.number 來檢索 --number。

options = getOptions(sys.argv[1:])
if options.verbose:
print("Verbose mode on")
else:
print("Verbose mode off")
print(options.input)
print(options.output)
print(options.number)
# 這裡插入你的 Python 代碼

示例中的布爾選項 --verbose 是通過測試 options.verbose 是否為 True(意味著用戶使用了 --verbose 標誌)或 False(用戶沒有使用 --verbose 標誌),並採取相應的措施。


幫助和反饋

argparse 還包含一個內置的 --help(簡寫 -h)選項,它提供了有關如何使用命令的提示。這是從你的代碼派生的,因此生成此幫助系統不需要額外的工作:

$ ./example.py --help
usage: example.py [-h] [-i INPUT] [-o OUTPUT] [-n NUMBER] [-v]
Parses command.
optional arguments:
-h, --help show this help message and exit
-i INPUT, --input INPUT
Your input file.
-o OUTPUT, --output OUTPUT
Your destination output file.
-n NUMBER, --number NUMBER
A number.
-v, --verbose Verbose mode.

像專業人士一樣用 Python 解析

這是一個簡單的示例,來演示如何在 Python 應用中的解析參數以及如何快速有效地記錄它的語法。下次編寫 Python 腳本時,請使用 argparse 為其提供一些選項。你以後會感到自得,你的命令不會像一個快速的臨時腳本,更像是一個「真正的」 Unix 命令!

以下是可用於測試的示例代碼:

#!/usr/bin/env python3
# GNU All-Permissive License
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.
import argparse
import sys
def getOptions(args=sys.argv[1:]):
parser = argparse.ArgumentParser(description="Parses command.")
parser.add_argument("-i", "--input", help="Your input file.")
parser.add_argument("-o", "--output", help="Your destination output file.")
parser.add_argument("-n", "--number", type=int, help="A number.")
parser.add_argument("-v", "--verbose",dest="verbose",action="store_true", help="Verbose mode.")
options = parser.parse_args(args)
return options
options = getOptions(sys.argv[1:])
if options.verbose:
print("Verbose mode on")
else:
print("Verbose mode off")
print(options.input)
print(options.output)
print(options.number)


via: https://opensource.com/article/19/7/parse-arguments-python

作者: Seth Kenlon 選題: lujun9972 譯者: geekpi 校對: wxy

本文由 LCTT 原創編譯, Linux中國 榮譽推出


點擊「了解更多」可訪問文內鏈接

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 Linux技術 的精彩文章:

命令行快速提示:許可權
如何管理你的 Linux 環境變數

TAG:Linux技術 |