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操作sqlite3快速、安全插入数据(防注入)的实例
Apr 26 Python
pycharm 使用心得(八)如何调用另一文件中的函数
Jun 06 Python
Python with的用法
Aug 22 Python
python自动化脚本安装指定版本python环境详解
Sep 14 Python
基于Django的python验证码(实例讲解)
Oct 23 Python
Python实现购物车程序
Apr 16 Python
python实现图片文件批量重命名
Mar 23 Python
python实现简易数码时钟
Feb 19 Python
python3使用QQ邮箱发送邮件
May 20 Python
python 中的列表生成式、生成器表达式、模块导入
Jun 19 Python
Python之指数与E记法的区别详解
Nov 21 Python
python shell命令行中import多层目录下的模块操作
Mar 09 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
wiki-shan写的php在线加密的解密程序
2008/09/07 PHP
fleaphp crud操作之findByField函数的使用方法
2011/04/23 PHP
php实现可以设置中奖概率的抽奖程序代码分享
2014/01/19 PHP
PHP把数字转成人民币大写的函数分享
2014/06/30 PHP
PHP实现简单爬虫的方法
2015/07/29 PHP
PHP 在数组中搜索给定的简单实例 array_search 函数
2016/06/13 PHP
php使用mysqli和pdo扩展,测试对比mysql数据库的执行效率完整示例
2019/05/09 PHP
javascript学习笔记(十二) RegExp类型介绍
2012/06/20 Javascript
JS加jquery简单实现标签元素的显示或隐藏
2013/09/23 Javascript
模拟一个类似百度google的模糊搜索下拉列表
2014/04/15 Javascript
Bootstrap导航栏各元素操作方法(表单、按钮、文本)
2015/12/28 Javascript
jQuery实现图片走马灯效果的原理分析
2016/01/16 Javascript
JS框架之vue.js(深入三:组件1)
2016/09/29 Javascript
js学习之----深入理解闭包
2016/11/21 Javascript
Vue-resource实现ajax请求和跨域请求示例
2017/02/23 Javascript
React-Native 组件之 Modal的使用详解
2017/08/08 Javascript
使用vue与jquery实时监听用户输入状态的操作代码
2017/09/19 jQuery
vuejs中监听窗口关闭和窗口刷新事件的方法
2018/09/21 Javascript
python TCP Socket的粘包和分包的处理详解
2018/02/09 Python
如何用python整理附件
2018/05/13 Python
python使用webdriver爬取微信公众号
2018/08/31 Python
python django下载大的csv文件实现方法分析
2019/07/19 Python
Django外键(ForeignKey)操作以及related_name的作用详解
2019/07/29 Python
Python 中的 global 标识对变量作用域的影响
2019/08/12 Python
python图形界面开发之wxPython树控件使用方法详解
2020/02/24 Python
Python多个装饰器的调用顺序实例解析
2020/05/22 Python
Python无损压缩图片的示例代码
2020/08/06 Python
Python3压缩和解压缩实现代码
2021/03/01 Python
Chicco婴儿用品美国官网:汽车座椅、婴儿推车、高脚椅等
2018/11/05 全球购物
一套中级Java程序员笔试题
2015/01/14 面试题
大学生应聘自荐信
2013/10/11 职场文书
专业技术职务聘任书
2014/03/29 职场文书
访谈节目策划方案
2014/05/15 职场文书
销售代理协议书
2014/09/30 职场文书
2014年班级工作总结范文
2014/12/23 职场文书
人物搭配车车超萌联名预备中 【咒术迴战】 ⨯ 【天竺鼠车车】 展开合作
2022/04/11 日漫