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下的XSLT API进行web开发的简单教程
Apr 15 Python
Python发送以整个文件夹的内容为附件的邮件的教程
May 06 Python
Python 使用requests模块发送GET和POST请求的实现代码
Sep 21 Python
python使用正则表达式替换匹配成功的组并输出替换的次数
Nov 22 Python
Python排序搜索基本算法之插入排序实例分析
Dec 11 Python
python中abs&map&reduce简介
Feb 20 Python
python的dataframe转换为多维矩阵的方法
Apr 11 Python
python smtplib发送带附件邮件小程序
May 22 Python
python:动态路由的Flask程序代码
Nov 22 Python
新手入门学习python Numpy基础操作
Mar 02 Python
Python selenium环境搭建实现过程解析
Sep 08 Python
python数字类型和占位符详情
Mar 13 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
CodeIgniter读写分离实现方法详解
2016/01/20 PHP
php中mkdir()函数的权限问题分析
2016/09/24 PHP
Laravel 5.5基于内置的Auth模块实现前后台登陆详解
2017/12/21 PHP
javascript 页面只自动刷新一次
2009/07/10 Javascript
Extjs入门之动态加载树代码
2010/04/09 Javascript
Jquery阻止事件冒泡 event.stopPropagation
2011/12/11 Javascript
javascript中encodeURI和decodeURI方法使用介绍
2013/05/06 Javascript
jQuery简单实现隐藏以及显示特效
2015/02/26 Javascript
面向切面编程(AOP)的理解
2015/05/01 Javascript
简介JavaScript中fixed()方法的使用
2015/06/08 Javascript
直接拿来用的15个jQuery代码片段
2015/09/23 Javascript
javascript表单处理具体实现代码(表单、链接、按钮)
2016/05/07 Javascript
详解XMLHttpRequest(一)同步请求和异步请求
2016/09/14 Javascript
JS实现图片高斯模糊切换效果的焦点图实例
2017/01/21 Javascript
微信小程序 动态绑定数据及动态事件处理
2017/03/14 Javascript
js防刷新的倒计时代码 js倒计时代码
2017/09/06 Javascript
微信小程序自动客服功能
2017/11/02 Javascript
Ionic学习日记实现验证码倒计时
2018/02/08 Javascript
Vue作用域插槽slot-scope实例代码
2018/09/05 Javascript
Vue.js组件实现选项卡以及切换特效
2019/07/24 Javascript
JavaScript实现京东放大镜效果
2019/12/03 Javascript
详细分析vue响应式原理
2020/06/22 Javascript
Python通过PIL获取图片主要颜色并和颜色库进行对比的方法
2015/03/19 Python
python创建进程fork用法
2015/06/04 Python
python numpy 反转 reverse示例
2019/12/04 Python
python开发实例之Python的Twisted框架中Deferred对象的详细用法与实例
2020/03/19 Python
python 调用Google翻译接口的方法
2020/12/09 Python
HTML5标签大全
2016/11/23 HTML / CSS
护理学专业推荐信
2013/12/03 职场文书
法人代表委托书
2014/04/04 职场文书
大学生就业自我推荐信
2014/05/10 职场文书
医院护士工作检讨书
2014/10/26 职场文书
初中数学课堂教学反思
2016/02/17 职场文书
小程序实现文字循环滚动动画
2021/06/14 Javascript
Python pandas读取CSV文件的注意事项(适合新手)
2021/06/20 Python
mongodb清除连接和日志的正确方法分享
2021/09/15 MongoDB