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

首頁 > 編程 > Python > 正文

python通過getopt模塊如何獲取執行的命令參數詳解

2020-02-16 11:23:01
字體:
來源:轉載
供稿:網友

前言

python腳本和shell腳本一樣可以獲取命令行的參數,根據不同的參數,執行不同的邏輯處理。

通常我們可以通過getopt模塊獲得不同的執行命令和參數。下面話不多說了,來一起看看詳細的介紹吧。

方法如下:

下面我通過新建一個test.py的腳本解釋下這個模塊的的使用

#!/usr/bin/python# -*- coding: utf-8 -*-import sysimport getoptif __name__=='__main__': print sys.argv opts, args = getopt.getopt(sys.argv[1:], "ht:q:", ["url=",'out']) print opts print args

執行命令 :

./test3.py -t 20171010-20171011 -q 24 -h --url=https://www.baidu.com --out file1 file2

執行結果 :

['D:/GitReposity/hope_crontab_repo/sla_channel/test3.py', '-t', '20171010-20171011', '-q', '24', '-h', '--url=https://www.baidu.com', '--out', 'file1', 'file2'][('-t', '20171010-20171011'), ('-q', '24'), ('-h', ''), ('--url', 'https://www.baidu.com'), ('--out', '')]['file1', 'file2']

我們查看getopt模塊的官方文檔

def getopt(args, shortopts, longopts = [])Parses command line options and parameter list. args is theargument list to be parsed, without the leading reference to therunning program. Typically, this means "sys.argv[1:]". shortoptsis the string of option letters that the script wants torecognize, with options that require an argument followed by acolon (i.e., the same format that Unix getopt() uses). Ifspecified, longopts is a list of strings with the names of thelong options which should be supported. The leading '--'characters should not be included in the option name. Optionswhich require an argument should be followed by an equal sign('=').The return value consists of two elements: the first is a list of(option, value) pairs; the second is the list of program argumentsleft after the option list was stripped (this is a trailing sliceof the first argument). Each option-and-value pair returned hasthe option as its first element, prefixed with a hyphen (e.g.,'-x'), and the option argument as its second element, or an emptystring if the option has no argument. The options occur in thelist in the same order in which they were found, thus allowingmultiple occurrences. Long and short options may be mixed.

可以發現getopt方法需要三個參數。

第一個參數是args是將要解析的命令行參數我們可以通過sys.argv獲取執行的相關參數

['D:/GitReposity/hope_crontab_repo/sla_channel/test3.py', '-t', '20171010-20171011', '-q', '24', '-h', '--url=https://www.baidu.com'] 

可以看出參數列表的第一個值是腳本執行的完全路徑名,剩余參數是以空格分割的命令行參數。為了獲得有效參數,通常args參數的值取sys.argv[1:]

第二個參數是shortopts是短命令操作符,他的參數要包含命令行中以 -符號開頭的參數,像上面的例子中qht都以為 -開頭,所以qht是該腳本的短命令,短命令又是如何匹配參數的呢?可以看到例子中shotopts為 "ht:q:" ,這里用命令后面跟著 : 來申明這個命令是否需要參數,這里h不需要參數,t和q需要參數,而命令行中緊跟著t和q的參數即為他們的命令參數,即t的命令參數為 20171010-20171011 ,q的命令參數為 24 。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 米易县| 荥阳市| 平远县| 绥化市| 正宁县| 揭阳市| 凌云县| 大丰市| 株洲县| 方山县| 逊克县| 盐山县| 永嘉县| 化隆| 百色市| 中阳县| 乐东| 松潘县| 手机| 堆龙德庆县| 枞阳县| 平顶山市| 铜鼓县| 二手房| 梧州市| 政和县| 株洲市| 阳春市| 利津县| 江陵县| 宿松县| 弋阳县| 丰顺县| 太康县| 枣阳市| 时尚| 建瓯市| 汕尾市| 开远市| 基隆市| 双江|