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 相关文章推荐
linux 下实现python多版本安装实践
Nov 18 Python
python抓取网页中图片并保存到本地
Dec 01 Python
django多文件上传,form提交,多对多外键保存的实例
Aug 06 Python
python支持多线程的爬虫实例
Dec 21 Python
Python pyautogui模块实现鼠标键盘自动化方法详解
Feb 17 Python
python去除删除数据中\u0000\u0001等unicode字符串的代码
Mar 06 Python
Python按照list dict key进行排序过程解析
Apr 04 Python
解决Opencv+Python cv2.imshow闪退问题
Apr 24 Python
Python Dict找出value大于某值或key大于某值的所有项方式
Jun 05 Python
Python decimal模块使用方法详解
Jun 08 Python
pycharm最新激活码有效期至2100年(亲测可用)
Feb 05 Python
python文件与路径操作神器 pathlib
Apr 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
PHP网站建设的流程与步骤分享
2015/09/25 PHP
php的闭包(Closure)匿名函数初探
2016/02/14 PHP
PHP使用Redis长连接的方法详解
2018/02/12 PHP
vs2003 js文件编码问题的解决方法
2010/03/20 Javascript
IE、FF、Chrome浏览器中的JS差异介绍
2013/08/13 Javascript
jquery中常用的SET和GET$(”#msg”).html循环介绍
2013/10/09 Javascript
js判断ie版本号的简单实现代码
2014/03/05 Javascript
JSON取值前判断
2014/12/23 Javascript
jQuery中before()方法用法实例
2014/12/25 Javascript
Lab.js初次使用笔记
2015/02/28 Javascript
javascript下拉框选项单击事件的例子分享
2015/03/04 Javascript
javascript日期计算实例分析
2015/06/29 Javascript
数组Array的排序sort方法
2017/02/17 Javascript
利用Vue.js框架实现火车票查询系统(附源码)
2017/02/27 Javascript
JS实现两周内自动登录功能
2017/03/23 Javascript
Node.js+jade抓取博客所有文章生成静态html文件的实例
2017/09/19 Javascript
利用jquery如何从json中读取数据追加到html中
2017/12/01 jQuery
原生JS实现DOM加载完成马上执行JS代码的方法
2018/09/07 Javascript
详解webpack编译速度提升之DllPlugin
2019/02/05 Javascript
使用 vue 实例更好的监听事件及vue实例的方法
2019/04/22 Javascript
Vue项目中配置pug解析支持
2019/05/10 Javascript
关于vue里页面的缓存详解
2019/11/04 Javascript
[51:53]完美世界DOTA2联赛决赛日 Inki vs LBZS 第二场 11.08
2020/11/10 DOTA
python使用PyCharm进行远程开发和调试
2017/11/02 Python
python爱心表白 每天都是浪漫七夕!
2018/08/18 Python
使用Python的toolz库开始函数式编程的方法
2018/11/15 Python
python实现替换word中的关键文字(使用通配符)
2020/02/13 Python
Python + selenium + crontab实现每日定时自动打卡功能
2020/03/31 Python
python文件编写好后如何实践
2020/07/07 Python
python 实现围棋游戏(纯tkinter gui)
2020/11/13 Python
电子信息专业学生自荐信
2013/11/09 职场文书
大学生通用个人自我评价
2014/04/27 职场文书
微笑服务标语
2014/06/24 职场文书
主持人大赛开场白
2015/05/29 职场文书
《我要的是葫芦》教学反思
2016/02/18 职场文书
DIY胆机必读:各国电子管评价
2022/04/06 无线电