国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python getopt模塊處理命令行選項實例

2019-11-25 18:25:14
字體:
來源:轉載
供稿:網友

getopt模塊用于抽出命令行選項和參數,也就是sys.argv
命令行選項使得程序的參數更加靈活。支持短選項模式和長選項模式
例如  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 ( [命令行參數列表], '短選項', [長選項列表] )

短選項名后的冒號 : 表示該選項必須有附加的參數
長選項名后的等號 = 表示該選項必須有附加的參數

返回 opts 和 args
opts 是一個參數選項及其value的元組 ( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args 是一個除去有用參數外其他的命令行輸入 ( 'a', 'b' )  

復制代碼 代碼如下:
# 然后遍歷 opts 便可以獲取所有的命令行選項及其對應參數了
for opt, val in opts:
    if opt in ( '-f', '--format' ):
        pass
    if ....

使用字典接受命令行的輸入,然后再傳送字典,可以使得命令行參數的接口更加健壯

# 兩個來自 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']

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南昌县| 大埔县| 赤水市| 和龙市| 横山县| 隆德县| 营山县| 台北市| 拉孜县| 河北区| 临泉县| 阜南县| 乌拉特前旗| 杨浦区| 襄汾县| 大丰市| 曲阜市| 宜黄县| 沂水县| 凤阳县| 克拉玛依市| 伽师县| 新乡县| 昌图县| 开封县| 会宁县| 高碑店市| 广宁县| 楚雄市| 旅游| 宜兰县| 报价| 格尔木市| 泊头市| 邵武市| 无极县| 全州县| 遂昌县| 周宁县| 贞丰县| 嘉荫县|