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实现SVN的目录周期性备份实例
Jul 17 Python
Python 编码处理-str与Unicode的区别
Sep 06 Python
Python正则表达式经典入门教程
May 22 Python
将tensorflow的ckpt模型存储为npy的实例
Jul 09 Python
想学python 这5本书籍你必看!
Dec 11 Python
python读取csv和txt数据转换成向量的实例
Feb 12 Python
详解Python 爬取13个旅游城市,告诉你五一大家最爱去哪玩?
May 07 Python
tensorflow模型文件(ckpt)转pb文件的方法(不知道输出节点名)
Apr 22 Python
Python pandas 列转行操作详解(类似hive中explode方法)
May 18 Python
Python必须了解的35个关键词
Jul 16 Python
python实现一个简单RPC框架的示例
Oct 28 Python
分布式全文检索引擎ElasticSearch原理及使用实例
Nov 14 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开发不能违背的安全规则 过滤用户输入
2011/05/01 PHP
PHP学习笔记 IIS7下安装配置php环境
2012/10/29 PHP
浅析PHP原理之变量(Variables inside PHP)
2013/08/09 PHP
php实现字符串首字母大写和单词首字母大写的方法
2015/03/14 PHP
Windows Server 2008 R2和2012中PHP连接MySQL过慢的解决方法
2016/07/02 PHP
Laravel如何使用数据库事务及捕获事务失败后的异常详解
2017/10/23 PHP
详解PHP的抽象类和抽象方法以及接口总结
2019/03/15 PHP
关于实现代码语法标亮 dp.SyntaxHighlighter
2007/02/02 Javascript
拥抱模块化的JavaScript
2012/03/07 Javascript
JavaScript数据结构与算法之栈与队列
2016/01/29 Javascript
Node.js重新刷新session过期时间的方法
2016/02/04 Javascript
js 实现获取name 相同的页面元素并循环遍历的方法
2017/02/14 Javascript
Three.js的使用及绘制基础3D图形详解
2017/04/27 Javascript
vue页面使用阿里oss上传功能的实例(一)
2017/08/09 Javascript
AngularJs导出数据到Excel的示例代码
2017/08/11 Javascript
Vue 框架之动态绑定 css 样式实例分析
2018/11/14 Javascript
在Vue项目中使用Typescript的实现
2019/12/19 Javascript
JavaScript中的函数式编程详解
2020/08/22 Javascript
基于Django与ajax之间的json传输方法
2018/05/29 Python
python numpy和list查询其中某个数的个数及定位方法
2018/06/27 Python
解决Pycharm出现的部分快捷键无效问题
2018/10/22 Python
在Python运行时动态查看进程内部信息的方法
2019/02/22 Python
Python 根据日志级别打印不同颜色的日志的方法示例
2019/08/08 Python
Python测试模块doctest使用解析
2019/08/10 Python
如何使用Python处理HDF格式数据及可视化问题
2020/06/24 Python
CSS3盒子模型详解
2013/04/24 HTML / CSS
意大利奢侈品零售商:ilDuomo Novara
2019/09/11 全球购物
澳大利亚手袋、珠宝和在线时尚精品店:The Way
2019/12/21 全球购物
初中政治教学反思
2014/01/17 职场文书
《陋室铭》教学反思
2014/02/26 职场文书
我的中国梦演讲稿1000字
2014/08/19 职场文书
质量承诺书格式范文
2015/04/28 职场文书
奖学金主要事迹范文
2015/11/04 职场文书
简历中的自我评价怎么写呢?
2019/04/30 职场文书
golang日志包logger的用法详解
2021/05/05 Golang
你真的了解redis为什么要提供pipeline功能
2021/06/22 Redis