python通过getopt模块如何获取执行的命令参数详解


Posted in Python onDecember 29, 2017

前言

python脚本和shell脚本一样可以获取命令行的参数,根据不同的参数,执行不同的逻辑处理。

通常我们可以通过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是短命令操作符,他的参数要包含命令行中以 -符号开头的参数,像上面的例子中qht都以为 -开头,所以qht是该脚本的短命令,短命令又是如何匹配参数的呢?可以看到例子中shotopts为 "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 相关文章推荐
浅析Python编写函数装饰器
Mar 18 Python
python list排序的两种方法及实例讲解
Mar 20 Python
Python使用selenium实现网页用户名 密码 验证码自动登录功能
May 16 Python
python中的tcp示例详解
Dec 09 Python
Python分布式进程中你会遇到的问题解析
May 28 Python
使用Flask-Cache缓存实现给Flask提速的方法详解
Jun 11 Python
Pycharm远程调试原理及具体配置详解
Aug 08 Python
Kears+Opencv实现简单人脸识别
Aug 28 Python
对Django的restful用法详解(自带的增删改查)
Aug 28 Python
django2.2安装错误最全的解决方案(小结)
Sep 24 Python
Pycharm配置PyQt5环境的教程
Apr 02 Python
Python数据可视化图实现过程详解
Jun 12 Python
基于并发服务器几种实现方法(总结)
Dec 29 #Python
Python matplotlib画图实例之绘制拥有彩条的图表
Dec 28 #Python
python操作列表的函数使用代码详解
Dec 28 #Python
Python读csv文件去掉一列后再写入新的文件实例
Dec 28 #Python
python3.6连接MySQL和表的创建与删除实例代码
Dec 28 #Python
python3使用scrapy生成csv文件代码示例
Dec 28 #Python
浅谈Scrapy框架普通反爬虫机制的应对策略
Dec 28 #Python
You might like
无数据库的详细域名查询程序PHP版(1)
2006/10/09 PHP
那些年一起学习的PHP(三)
2012/03/22 PHP
php使用glob函数快速查询指定目录文件的方法
2014/11/15 PHP
2款PHP无限级分类实例代码
2015/11/11 PHP
关于PHP文件的自动运行方法分析
2016/05/13 PHP
linux下php上传文件注意事项
2016/06/11 PHP
PHP实现的猴王算法(猴子选大王)示例
2018/04/30 PHP
javascript第一课
2007/02/27 Javascript
JavaScript设置FieldSet展开与收缩
2009/05/15 Javascript
Jquery实现鼠标移上弹出提示框、移出消失思路及代码
2013/05/19 Javascript
Js实现动态添加删除Table行示例
2014/04/14 Javascript
jQuery中:first选择器用法实例
2014/12/30 Javascript
javascript实现可键盘控制的抽奖系统
2016/03/10 Javascript
JS动态生成年份和月份实例代码
2017/02/04 Javascript
canvas实现动态小球重叠效果
2017/02/06 Javascript
AngularJS前端页面操作之用户修改密码功能示例
2017/03/27 Javascript
ES6学习笔记之正则表达式和字符串正则方法分析
2017/04/25 Javascript
JavaScript求一组数的最小公倍数和最大公约数常用算法详解【面向对象,回归迭代和循环】
2018/05/07 Javascript
jQuery实现轮播图及其原理详解
2020/04/12 jQuery
webpack-url-loader 解决项目中图片打包路径问题
2019/02/15 Javascript
解决vue打包后vendor.js文件过大问题
2019/07/03 Javascript
d3.js实现图形拖拽
2019/12/19 Javascript
js前端对于大量数据的展示方式及处理方法
2020/12/02 Javascript
[50:58]2018DOTA2亚洲邀请赛3月29日 小组赛A组OpTic VS Newbee
2018/03/30 DOTA
python打开文件并获取文件相关属性的方法
2015/04/23 Python
Python使用Django实现博客系统完整版
2020/09/29 Python
Opencv-Python图像透视变换cv2.warpPerspective的示例
2019/04/11 Python
python爬虫增加访问量的方法
2019/08/22 Python
pycharm中使用request和Pytest进行接口测试的方法
2020/07/31 Python
trivago美国:全球最大的酒店价格比较网站
2018/01/18 全球购物
市场营销专科应届生求职信
2013/11/24 职场文书
远程研修随笔感言
2014/02/10 职场文书
员工薪酬激励方案
2014/06/13 职场文书
2015小学语文教师个人工作总结
2015/05/20 职场文书
pytorch中[..., 0]的用法说明
2021/05/20 Python
flex布局中使用flex-wrap实现换行的项目实践
2022/06/21 HTML / CSS