Python getopt模块命令行参数解析详解

半杯拿铁
半杯拿铁
发布时间:2026-10-13 | 3人浏览过
原创

本文详解Python中getopt模块的使用方法,通过解析sys.argv获取命令行参数。介绍短选项(shortopts)和长选项(longopts)的定义规则,包括参数标识符、冒号及等号的作用。通过示例展示如何区分需参与不需参选项,并解析返回值中的选项元组与剩余参数,帮助开发者构建灵活的脚本逻辑。

前言

Python脚本与Shell脚本类似,能够接收并处理命令行传入的参数,依据不同的参数执行相应的逻辑分支。

在Python中,通常借助getopt模块来解析执行命令及其附带参数。接下来将详细介绍具体实现方式。

具体方法如下:

下面通过创建一个名为test.py的脚本来演示该模块的实际应用。

#!/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

执行结果输出:

['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 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函数主要接收三个参数。

第一个参数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用于定义短命令操作符,其字符串内容需包含命令行中以单横杠(-)开头的参数。例如前例中的q、h、t均以单横杠开头,故它们被视为短命令。短命令如何与参数关联?观察示例中shortopts值为"ht:q:",这里通过命令后紧跟冒号(:)来声明该命令是否接受参数。其中h不需要参数,而t和q需要参数。命令行中紧跟在t和q之后的值即为对应的命令参数,例如t的参数为20171010-20171011,q的参数为24。

第三个参数longopts是一个列表,表示长命令操作符集合。该集合需包含命令行中以双横杠(--)开头的参数。例如url和out均为长命令。当长命令定义后以等号(=)结尾时,表示该命令需要接收参数,如"url=",它将匹配命令行中紧随其后的参数值https://www.baidu.com。

该方法返回包含两个元素的元组。第一个返回值是由shortopts和longopts匹配得到的命令行选项及其参数的元组列表。本例的返回结果如下:

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

第二个返回值是命令行中未被匹配到的剩余参数列表,本例的返回结果为:

['file1', 'file2']

通过解析上述返回值,开发者可以在代码中根据不同命令设计多样化的处理逻辑,从而显著提升脚本的可用性和灵活性。

总结

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对本站的支持。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表