首页 > 编程 > 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 。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表