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二叉树的实现实例
Nov 21 Python
Python遍历目录并批量更换文件名和目录名的方法
Sep 19 Python
Python中字符串格式化str.format的详细介绍
Feb 17 Python
python初学之用户登录的实现过程(实例讲解)
Dec 23 Python
python学生信息管理系统(初级版)
Oct 17 Python
Python玩转Excel的读写改实例
Feb 22 Python
Python 抓取微信公众号账号信息的方法
Jun 14 Python
python opencv实现证件照换底功能
Aug 19 Python
python打印直角三角形与等腰三角形实例代码
Oct 20 Python
Python通过Manager方式实现多个无关联进程共享数据的实现
Nov 07 Python
python3实现绘制二维点图
Dec 04 Python
Python数据类型最全知识总结
May 31 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面试题(对属性或方法的访问控制)
2012/09/13 PHP
php jquery 多文件上传简单实例
2013/12/23 PHP
PHP解决中文乱码
2017/04/28 PHP
JQuery与iframe交互实现代码
2009/12/24 Javascript
JavaScript 拾漏补遗
2009/12/27 Javascript
JavaScript DOM 学习第五章 表单简介
2010/02/19 Javascript
Jquery 插件学习实例1 插件制作说明与tableUI优化
2010/04/02 Javascript
jquery 图片 上一张 下一张 链接效果(续篇)
2010/04/20 Javascript
jquery使用jquery.zclip插件复制对象的实例教程
2013/12/04 Javascript
jquery对table中各数据的增加、保存、删除操作示例
2014/05/14 Javascript
轻松创建nodejs服务器(2):nodejs服务器的构成分析
2014/12/18 NodeJs
js简单判断flash是否加载完成的方法
2016/06/21 Javascript
给vue项目添加ESLint的详细步骤
2017/09/29 Javascript
Vue Socket.io源码解读
2018/02/07 Javascript
vue2.0 elementUI制作面包屑导航栏
2018/02/22 Javascript
vue toggle做一个点击切换class(实例讲解)
2018/03/13 Javascript
vue仿element实现分页器效果
2018/09/13 Javascript
vue-cli+axios实现文件上传下载功能(下载接收后台返回文件流)
2019/05/10 Javascript
关于vue里页面的缓存详解
2019/11/04 Javascript
jQuery实现增删改查
2020/12/22 jQuery
Python查询IP地址归属完整代码
2017/06/21 Python
python中将函数赋值给变量时需要注意的一些问题
2017/08/18 Python
python实现txt文件格式转换为arff格式
2018/05/31 Python
Python图像处理之图片文字识别功能(OCR)
2019/07/30 Python
在win64上使用bypy进行百度网盘文件上传功能
2020/01/02 Python
在Django中自定义filter并在template中的使用详解
2020/05/19 Python
PyInstaller的安装和使用的详细步骤
2020/06/02 Python
泰国在线书店:SE-ED
2020/06/21 全球购物
Bandier官网:奢侈、时尚前卫的健身服装首选目的地
2020/07/05 全球购物
总经理岗位职责范本
2014/02/02 职场文书
2014公司党员自我评价范文
2014/09/11 职场文书
2014年大学班级工作总结
2014/11/14 职场文书
离退休人员聘用协议书
2014/11/24 职场文书
Python time库的时间时钟处理
2021/05/02 Python
科普 | 业余无线电知识-波段篇
2022/02/18 无线电
Redis安装使用RedisJSON模块的方法
2022/03/23 Redis