Python getopt模塊處理命令行選項(xiàng)實(shí)例
getopt模塊用于抽出命令行選項(xiàng)和參數(shù),也就是sys.argv
命令行選項(xiàng)使得程序的參數(shù)更加靈活。支持短選項(xiàng)模式和長(zhǎng)選項(xiàng)模式
例如 python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'
import getopt, sys
shortargs = 'f:t'
longargs = ['directory-prefix=', 'format']
opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )
getopt.getopt ( [命令行參數(shù)列表], '短選項(xiàng)', [長(zhǎng)選項(xiàng)列表] )
短選項(xiàng)名后的冒號(hào) : 表示該選項(xiàng)必須有附加的參數(shù)
長(zhǎng)選項(xiàng)名后的等號(hào) = 表示該選項(xiàng)必須有附加的參數(shù)
返回 opts 和 args
opts 是一個(gè)參數(shù)選項(xiàng)及其value的元組 ( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args 是一個(gè)除去有用參數(shù)外其他的命令行輸入 ( 'a', 'b' )
for opt, val in opts:
if opt in ( '-f', '--format' ):
pass
if ....
使用字典接受命令行的輸入,然后再傳送字典,可以使得命令行參數(shù)的接口更加健壯
# 兩個(gè)來(lái)自 python2.5 Documentation 的例子
>>> import getopt, sys
>>> arg = '-a -b -c foo -d bar a1 a2'
>>> optlist, args = getopt.getopt( sys.argv[1:], 'abc:d:' )
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
>>> arg = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> optlist, args = getopt.getopt( sys.argv[1:], 'x', ['condition=', 'output-file=', 'testing'] )
>>> optlist
[ ('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x','') ]
>>> args
['a1', 'a2']
相關(guān)文章
python根據(jù)json數(shù)據(jù)畫疫情分布地圖的詳細(xì)代碼
這篇文章主要介紹了python根據(jù)json數(shù)據(jù)畫疫情分布地圖的詳細(xì)代碼,掌握使用pyecharts構(gòu)建基礎(chǔ)的全國(guó)地圖可視化圖表,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12
python在windows下創(chuàng)建隱藏窗口子進(jìn)程的方法
這篇文章主要介紹了python在windows下創(chuàng)建隱藏窗口子進(jìn)程的方法,涉及Python使用subprocess模塊操作進(jìn)程的相關(guān)技巧,需要的朋友可以參考下2015-06-06
搞定這套Python爬蟲面試題(面試會(huì)so easy)
Python 是一門開源的解釋性語(yǔ)言,相比 Java C++ 等語(yǔ)言,Python 具有動(dòng)態(tài)特性,非常靈活。這篇文章主要介紹了搞定這套Python爬蟲面試題,面試會(huì)so easy,需要的朋友可以參考下2019-04-04
Python列表切片操作實(shí)例探究(提取復(fù)制反轉(zhuǎn))
在Python中,列表切片是處理列表數(shù)據(jù)非常強(qiáng)大且靈活的方法,本文將全面探討Python中列表切片的多種用法,包括提取子列表、復(fù)制列表、反轉(zhuǎn)列表等操作,結(jié)合豐富的示例代碼進(jìn)行詳細(xì)講解2024-01-01
分析Python list操作為什么會(huì)錯(cuò)誤
這篇文章主要介紹了分析Python list操作為什么會(huì)錯(cuò)誤,python搞數(shù)據(jù)分析,在很多方面python有著比Matlab更大的優(yōu)勢(shì),下面來(lái)看看文章具體介紹的相關(guān)內(nèi)容吧,需要的朋友可以參考一下2021-11-11
Python使用pymupdf實(shí)現(xiàn)PDF加密
這篇文章主要介紹了如何使用 Python 和 wxPython 庫(kù)創(chuàng)建一個(gè)簡(jiǎn)單的圖形用戶界面(GUI)應(yīng)用程序,用于對(duì) PDF 文件進(jìn)行加密,感興趣的小伙伴可以了解下2023-08-08

