自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用Python解析參數(shù)

開發(fā) 后端
如果你在使用 Python 進(jìn)行開發(fā),你可能會(huì)在終端中使用命令,即使只是為了啟動(dòng) Python 腳本或使用 pip 安裝 Python 模塊。

 [[271723]]

使用 argparse 模塊像專業(yè)人士一樣解析參數(shù)。

如果你在使用 Python 進(jìn)行開發(fā),你可能會(huì)在終端中使用命令,即使只是為了啟動(dòng) Python 腳本或使用 pip 安裝 Python 模塊。命令可能簡(jiǎn)單而單一:

  1. $ ls

命令也可能需要參數(shù):

  1. $ ls example

命令也可以有選項(xiàng)或標(biāo)志:

  1. $ ls --color example

有時(shí)選項(xiàng)也有參數(shù):

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

參數(shù)

POSIX shell 會(huì)自動(dòng)將你輸入的內(nèi)容作為命令分成數(shù)組。例如,這是一個(gè)簡(jiǎn)單的命令:

  1. $ ls example

命令 ls 的位置是 $0,參數(shù) example 位置是 $1。

可以寫一個(gè)循環(huán)迭代每項(xiàng)。確定它是否是命令、選項(xiàng)還是參數(shù)。并據(jù)此采取行動(dòng)。幸運(yùn)的是,已經(jīng)有一個(gè)名為 argparse 的模塊。

argparse

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

要在應(yīng)用中使用 argparse,首先要定義為用戶提供的選項(xiàng)。你可以接受幾種不同的參數(shù),而語法一致又簡(jiǎn)單。

這是一個(gè)簡(jiǎn)單的例子:

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

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

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

如果你有一個(gè)只是關(guān)閉和打開功能的參數(shù),那么你必須使用 boolean 類型,就像示例代碼中的 --verbose 標(biāo)志一樣。這種選項(xiàng)只保存 TrueFalse,用戶用來指定是否使用標(biāo)志。如果使用該選項(xiàng),那么會(huì)激活 stored_true。

當(dāng) getOptions 函數(shù)運(yùn)行時(shí),你就可以使用 options 對(duì)象的內(nèi)容,并讓程序根據(jù)用戶調(diào)用命令的方式做出決定。你可以使用測(cè)試打印語句查看 options 的內(nèi)容。將其添加到示例文件的底部:

  1. print(getOptions())

然后帶上參數(shù)運(yùn)行代碼:

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

檢索值

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

  1. options = getOptions(sys.argv[1:])
  2.  
  3. if options.verbose:
  4.     print("Verbose mode on")
  5. else:
  6.     print("Verbose mode off")
  7.  
  8. print(options.input)
  9. print(options.output)
  10. print(options.number)
  11.  
  12. # 這里插入你的 Python 代碼

示例中的布爾選項(xiàng) --verbose 是通過測(cè)試 options.verbose 是否為 True(意味著用戶使用了 --verbose 標(biāo)志)或 False(用戶沒有使用 --verbose 標(biāo)志),并采取相應(yīng)的措施。

幫助和反饋

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

  1. $ ./example.py --help
  2. usage: example.py [-h] [-i INPUT] [-o OUTPUT] [-n NUMBER] [-v]
  3.  
  4. Parses command.
  5.  
  6. optional arguments:
  7.   -h, --help            show this help message and exit
  8.   -i INPUT, --input INPUT
  9.                         Your input file.
  10.   -o OUTPUT, --output OUTPUT
  11.                         Your destination output file.
  12.   -n NUMBER, --number NUMBER
  13.                         A number.
  14.   -v, --verbose         Verbose mode.

像專業(yè)人士一樣用 Python 解析

這是一個(gè)簡(jiǎn)單的示例,來演示如何在 Python 應(yīng)用中的解析參數(shù)以及如何快速有效地記錄它的語法。下次編寫 Python 腳本時(shí),請(qǐng)使用 argparse 為其提供一些選項(xiàng)。你以后會(huì)感到自得,你的命令不會(huì)像一個(gè)快速的臨時(shí)腳本,更像是一個(gè)“真正的” Unix 命令!

以下是可用于測(cè)試的示例代碼:

  1. #!/usr/bin/env python3
  2. # GNU All-Permissive License
  3. # Copying and distribution of this file, with or without modification,
  4. # are permitted in any medium without royalty provided the copyright
  5. # notice and this notice are preserved.  This file is offered as-is,
  6. # without any warranty.
  7.  
  8. import argparse
  9. import sys
  10.  
  11. def getOptions(args=sys.argv[1:]):
  12.     parser = argparse.ArgumentParser(description="Parses command.")
  13.     parser.add_argument("-i", "--input", help="Your input file.")
  14.     parser.add_argument("-o", "--output", help="Your destination output file.")
  15.     parser.add_argument("-n", "--number", type=int, help="A number.")
  16.     parser.add_argument("-v", "--verbose",dest='verbose',action='store_true', help="Verbose mode.")
  17.     options = parser.parse_args(args)
  18.     return options
  19.  
  20. options = getOptions(sys.argv[1:])
  21.  
  22. if options.verbose:
  23.     print("Verbose mode on")
  24. else:
  25.     print("Verbose mode off")
  26.  
  27. print(options.input)
  28. print(options.output)
  29. print(options.number)

責(zé)任編輯:龐桂玉 來源: Linux中國
相關(guān)推薦

2021-11-15 14:30:49

Pythonargparse編程語言

2010-02-22 17:12:34

Python對(duì)象

2022-12-06 11:57:54

Lua參數(shù)

2022-07-13 16:06:16

Python參數(shù)代碼

2010-03-15 10:49:57

Python函數(shù)變量

2021-07-05 12:09:58

Python編程語言

2021-11-08 10:45:07

Python命令工具

2021-03-27 10:54:34

Python函數(shù)代碼

2010-02-03 09:19:31

Python模塊

2021-05-12 10:17:15

Shell工具Linux

2010-03-04 10:56:52

JVM參數(shù)

2014-05-15 10:07:29

2010-04-19 17:08:01

Oracle參數(shù)

2024-04-29 07:38:20

PythonDocopt開發(fā)

2022-11-08 11:49:09

NLP庫Python云服務(wù)

2018-02-23 11:11:11

PythonUrllibURL

2010-01-06 15:16:58

Ubuntu啟動(dòng)流程

2020-11-23 10:48:39

Golang GinW

2010-01-28 13:15:43

C++參數(shù)

2010-04-08 16:05:49

Unix操作系統(tǒng)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)