Python模块(1)-Argparse 简易使用教程
argparse 簡易使用教程
- 1基本函數
- 2例子程序演示
- 3常用參數解釋
- 4argparse模塊整理的緣起
1基本函數
argparse是Python中用于命令行中進行參數解析的一個模塊,可以自動生成help和usage信息;當從終端輸入的參數無效時,模塊會輸出提示信息。
Argparse常用的三個函數:
parser=Argparse.ArgumentParser()
ArgumentParser()用于創建一個ArgumentParser對象parser,parser保存了所有必要信息,用于將“從命令行中讀入的參數”解析為對應的python數據類型。
parser.add_argument()
用于給parser添加需要讀取數據的信息,這些信息告訴parser解析讀入參數的方法
args = parser.parse_args()
用于解析parser保存的參數,返回一個命名空間
在實際python腳本中parse_args()一般不使用參數,它的參數由sys.argv確定。
2例子程序演示
將下列代碼存成.py文件,在終端中運行。
import argparse parser=argparse.ArgumentParser(description="process some integer.") parser.add_argument('integers',metavar='N',type=int,nargs='+',help='an integer for accumulator') parser.add_argument('--sum',dest='accumulate',action='store_const',const=sum,default=max,help='sum the integers (default:find the max)' args=parser.parse_args() print(args.accumulate(args.integers))
上面程序實現了,默認求最大,可選求和的功能,結合上面程序,講解三個函數中常用的選項含義:
3常用參數解釋
parser=argparse.ArgumentParser(description=“process some integer.”)
1.1description,用于簡要介紹程序的功能和工作原理。在幫助消息中,說明顯示在 命令行‘用法’字符串 和 各種參數的幫助消息之間。
1.2prog,用于顯示“程序文件名”,默認為“運行文件名”
1.3usage,程序使用說明。當使用了 usage 的參數之后,會覆蓋覆蓋了 prog 參數里面的值。
parser.add_argument(‘integers’,metavar=‘N’,type=int,nargs=’+’,help=‘an integer for accumulator’)
parser.add_argument(’–sum’,dest=‘accumulate’,action=‘store_const’,const=sum,default=max, help=‘sum the integers (default:find the max)’)
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
2.1 name,用于保存輸入變量
2.2 action=‘store_const’ 存儲由const關鍵字參數指定的值。
2.3 nargs單個命令行參數與要執行的單個操作相關聯
2.4 default值是一個字符串,則解析器會將該值解析為一個命令行參數,變量的默認輸入
2.5 type 指定變量的類型
2.6 nargs=’+’.’+‘和’*'一樣,出現的所有命令行參數都被收集到一個列表中。
2.7 當ArgumentParser生成幫助信息時, 默認情況下使用dest的值作為每個對象的“名字”。
2.8 metavar會改變顯示出來的名字 - parse_args() 對象中屬性的名字仍然由dest的值決定。
(metavar: 這個參數用于help 信息輸出中)
args=parser.parse_args()
調用 parse_args() 將返回一個具有兩個屬性的對象, integers 和 accumulate 。
print(args.accumulate(args.integers))
累和的語句實現,默認對輸入的數據進行球最大,如果解析到sum的參數,那么求和
4argparse模塊整理的緣起
在程序會見到最簡單的形式,指定,參數類型,可選值,默認值,和幫助信息等,在運行程序的時候可以通過命令行輸入用戶制定的參數,否則使用默認參數。
parser.add_argument(’–cuda’, action=‘store_true’, help=‘enables cuda’)
當在終端運行的時候,如果不加入–cuda, 那么程序運行時的時候,–cuda的值為default: False
如果加上了–cuda,不需要指定True/False,那么程序運行的時候,–cuda的值為True
等價與一個開關操作.
更多內容可以詳見以下兩篇博文:
https://cloud.tencent.com/developer/section/1370514
https://www.cnblogs.com/piperck/p/8446580.html
https://blog.csdn.net/LemonTree_Summer/article/details/80749359
總結
以上是生活随笔為你收集整理的Python模块(1)-Argparse 简易使用教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux终端命令(6)--ifconf
- 下一篇: 《C++ Primer 5th》笔记(7