python經過getopt模塊獲取執行命令參數

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

一般咱們能夠經過getopt模塊得到不一樣的執行命令和參數。
下面我經過新建一個test.py的腳本解釋下這個模塊的的使用shell

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import getopt
if __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數組

執行結果 :ui

['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 = [])this

Parses command line options and parameter list.  args is the
argument list to be parsed, without the leading reference to the
running program.  Typically, this means "sys.argv[1:]".  shortopts
is the string of option letters that the script wants to
recognize, with options that require an argument followed by a
colon (i.e., the same format that Unix getopt() uses).  If
specified, longopts is a list of strings with the names of the
long options which should be supported.  The leading '--'
characters should not be included in the option name.  Options
which 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 arguments
left after the option list was stripped (this is a trailing slice
of the first argument).  Each option-and-value pair returned has
the option as its first element, prefixed with a hyphen (e.g.,
'-x'), and the option argument as its second element, or an empty
string if the option has no argument.  The options occur in the
list in the same order in which they were found, thus allowing
multiple occurrences.  Long and short options may be mixed.

能夠發現getopt方法須要三個參數。url

第一個參數是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的命令參數爲 24code

第三個參數是longopts,改參數是個數組, 表示長命令操做符集合。這個集合要包含命令行中以 -- 符號開頭的參數,url和out都是長命令,當長命令後面以 = 結尾是表示他須要一個參數,好比"url=" ,他匹配命令行中的下一個參數https://www.baidu.com.orm

該方法返回兩個數組元素。第一個返回值,是經過shortoptslongopts匹配的命令行和其參數的元祖。該例子的返回值爲:

[('-t', '20171010-20171011'), ('-q', '24'), ('-h', ''), ('--url', 'https://www.baidu.com'), ('--out', '')]
['file1', 'file2']

第二個返回值是命令行中未被匹配到的參數,該例子的返回值爲:

['file1', 'file2']

經過返回值咱們就能夠在本身的代碼中,根據不一樣命令去設計不一樣的邏輯處理,至關豐富了腳本的可用性。

相關文章
相關標籤/搜索