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的身份证号码自动生成程序
Aug 15 Python
python基础教程之序列详解
Aug 29 Python
在Python中测试访问同一数据的竞争条件的方法
Apr 23 Python
Jupyter notebook远程访问服务器的方法
May 24 Python
python3 打印输出字典中特定的某个key的方法示例
Jul 06 Python
Django实现任意文件上传(最简单的方法)
Jun 03 Python
sklearn的predict_proba使用说明
Jun 28 Python
五分钟学会怎么用Pygame做一个简单的贪吃蛇
Jan 06 Python
python中用ggplot绘制画图实例讲解
Jan 26 Python
Pytorch中的数据集划分&正则化方法
May 27 Python
Python之基础函数案例详解
Aug 30 Python
python实现手机推送 代码也就10行左右
Apr 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模拟ping命令(php exec函数的使用方法)
2013/10/25 PHP
PHP根据传入参数合并多个JS和CSS文件的简单实现
2014/06/13 PHP
php实现扫描二维码根据浏览器类型访问不同下载地址
2014/10/15 PHP
php封装db类连接sqlite3数据库的方法实例
2017/12/19 PHP
基于swoole实现多人聊天室
2018/06/14 PHP
用JavaScript将从数据库中读取出来的日期型格式化为想要的类型。
2009/08/15 Javascript
JS 实现完美include载入实现代码
2010/08/05 Javascript
jquery EasyUI的formatter格式化函数代码
2011/01/12 Javascript
jquery post方式传递多个参数值后台以数组的方式进行接收
2013/01/11 Javascript
检查输入的是否是数字使用keyCode配合onkeypress事件
2014/01/23 Javascript
For循环中分号隔开的3部分的执行顺序探讨
2014/05/27 Javascript
详解JavaScript中setSeconds()方法的使用
2015/06/11 Javascript
JavaScript iframe数据共享接口实现方法
2016/01/06 Javascript
javascript判断图片是否加载完成的方法推荐
2016/05/13 Javascript
VUEJS实战之构建基础并渲染出列表(1)
2016/06/13 Javascript
jQuery 实时保存页面动态添加的数据的示例
2017/08/14 jQuery
javascript面向对象三大特征之继承实例详解
2019/07/24 Javascript
jQuery AJAX应用实例总结
2020/05/19 jQuery
python类继承与子类实例初始化用法分析
2015/04/17 Python
python数据抓取分析的示例代码(python + mongodb)
2017/12/25 Python
Python3.5.3下配置opencv3.2.0的操作方法
2018/04/02 Python
10分钟教你用python动画演示深度优先算法搜寻逃出迷宫的路径
2019/08/12 Python
Django中从mysql数据库中获取数据传到echarts方式
2020/04/07 Python
Keras 中Leaky ReLU等高级激活函数的用法
2020/07/05 Python
Python爬虫实例之2021猫眼票房字体加密反爬策略(粗略版)
2021/02/22 Python
萨克斯第五大道英国:Saks Fifth Avenue英国
2019/04/01 全球购物
Osklen官方在线商店:巴西服装品牌
2019/04/25 全球购物
explicit和implicit的含义
2012/11/15 面试题
应届生求职信写作技巧
2013/10/24 职场文书
电子商务专员岗位职责
2013/12/11 职场文书
《夜晚的实验》教学反思
2014/02/19 职场文书
党员群众路线承诺书
2014/05/20 职场文书
干部职工纪律作风整改措施思想汇报
2014/10/11 职场文书
2015年重阳节慰问信
2015/03/23 职场文书
2015年出纳年终工作总结
2015/05/14 职场文书
2016年社区综治宣传月活动总结
2016/03/16 职场文书