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的命令参数为 24 。code
第三个参数是longopts,改参数是个数组, 表示长命令操做符集合。这个集合要包含命令行中以 -- 符号开头的参数,url和out都是长命令,当长命令后面以 = 结尾是表示他须要一个参数,好比"url=" ,他匹配命令行中的下一个参数https://www.baidu.com.orm
该方法返回两个数组元素。第一个返回值,是经过shortopts和longopts匹配的命令行和其参数的元祖。该例子的返回值为:
[('-t', '20171010-20171011'), ('-q', '24'), ('-h', ''), ('--url', 'https://www.baidu.com'), ('--out', '')] ['file1', 'file2']
第二个返回值是命令行中未被匹配到的参数,该例子的返回值为:
['file1', 'file2']
经过返回值咱们就能够在本身的代码中,根据不一样命令去设计不一样的逻辑处理,至关丰富了脚本的可用性。