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中用Descriptor实现类级属性(Property)详解
Sep 18 Python
在Python的框架中为MySQL实现restful接口的教程
Apr 08 Python
Python的Django框架中if标签的相关使用
Jul 15 Python
Python的包管理器pip更换软件源的方法详解
Jun 20 Python
django初始化数据库的实例
May 27 Python
python 常用的基础函数
Jul 10 Python
Python简单过滤字母和数字的方法小结
Jan 09 Python
Django项目创建到启动详解(最全最详细)
Sep 07 Python
利用python在excel中画图的实现方法
Mar 17 Python
对python中各个response的使用说明
Mar 28 Python
Python常见反爬虫机制解决方案
Jun 01 Python
Python合并pdf文件的工具
Jul 01 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
dedecms系统的广告设置代码 基础版本
2010/04/09 PHP
php strcmp使用说明
2010/04/22 PHP
php配置php-fpm启动参数及配置详解
2013/11/04 PHP
ThinkPHP使用PHPExcel实现Excel数据导入导出完整实例
2014/07/22 PHP
Laravel 5框架学习之表单
2015/04/08 PHP
PHP检测接口Traversable用法详解
2017/12/29 PHP
PHP超全局变量实现原理及代码解析
2020/09/01 PHP
利用jQuary实现文字浮动提示效果示例代码
2013/12/26 Javascript
js数组循环遍历数组内所有元素的方法
2014/01/18 Javascript
js修改原型的属性使用介绍
2014/01/26 Javascript
Jquery实现控件的隐藏和显示实例
2014/02/08 Javascript
nodejs爬虫抓取数据之编码问题
2015/07/03 NodeJs
JS+CSS实现大气的黑色首页导航菜单效果代码
2015/09/10 Javascript
js实现内容显示并使用json传输数据
2016/03/16 Javascript
分析js闭包引起的事件注册问题
2016/03/29 Javascript
前端框架Vue.js中Directive知识详解
2016/09/12 Javascript
jQuery模拟Marquee实现无缝滚动效果完整实例
2016/09/29 Javascript
JavaScript获取中英文混合字符串长度的方法示例
2017/02/04 Javascript
使用requirejs模块化开发多页面一个入口js的使用方式
2017/06/14 Javascript
vue.js 双层嵌套for遍历的方法详解, 类似php foreach()
2018/09/07 Javascript
[01:16:13]DOTA2-DPC中国联赛 正赛 SAG vs Dragon BO3 第一场 2月22日
2021/03/11 DOTA
python去掉空白行的多种实现代码
2018/03/19 Python
python如何实现数据的线性拟合
2019/07/19 Python
python构造函数init实例方法解析
2020/01/19 Python
详解有关PyCharm安装库失败的问题的解决方法
2020/02/02 Python
python turtle工具绘制四叶草的实例分享
2020/02/14 Python
Python基于read(size)方法读取超大文件
2020/03/12 Python
python 两个一样的字符串用==结果为false问题的解决
2020/03/12 Python
西班牙三叶草药房:Farmacias Trébol
2019/05/03 全球购物
Wolford法国官网:奥地利奢侈内衣品牌
2020/08/11 全球购物
实习生的自我鉴定范文欣赏
2013/11/20 职场文书
大学生实习感言
2014/01/16 职场文书
优秀党员主要事迹
2014/01/19 职场文书
竞选大队干部演讲稿
2014/09/11 职场文书
2014年保卫部工作总结
2014/11/21 职场文书
《总之就是很可爱》新作短篇动画《总之就是很可爱~制服~》将于2022年夏天播出
2022/04/07 日漫