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.

该方法返回两个数组元素。第一个返回值,是通过shortoptslongopts匹配的命令行和其参数的元祖。该例子的返回值为:

[('-t', '20171010-20171011'), ('-q', '24'), ('-h', ''), ('--url', 'https://www.baidu.com'), ('--out', '')]
['file1', 'file2']

第二个返回值是命令行中未被匹配到的参数,该例子的返回值为:

['file1', 'file2']

通过返回值我们就可以在自己的代码中,根据不同命令去设计不同的逻辑处理,相当丰富了脚本的可用性。

python通过getopt模块获取执行命令参数的更多相关文章

  1. Python之getopt模块

    1.getopt——C风格命令行解析 http://docs.python.org/2.7/library/getopt.html#module-getopt getopt.getopt(args, ...

  2. Python通过paramiko批量远程主机执行命令

    一.前言 在日常运维的过程中,经常需要登录主机去执行一些命令,有时候需要登录一批主机执行相同的命,手动登录执行的化效率太慢, 所以可以通过Python的paramiko模块批量执行,本篇文章基于pyt ...

  3. python封装configparser模块获取conf.ini值(优化版)

    昨天晚上封装了configparser模块,是根据keyname获取的value.python封装configparser模块获取conf.ini值 我原本是想通过config.ini文件中的sect ...

  4. python使用wmi模块获取windows下的系统信息监控系统-乾颐堂

    Python用WMI模块获取Windows系统的硬件信息:硬盘分区.使用情况,内存大小,CPU型号,当前运行的进程,自启动程序及位置,系统的版本等信息. 本文实例讲述了python使用wmi模块获取w ...

  5. python之实现批量远程执行命令(堡垒机)

    python远程批量执行 我并不是一个专业的开发,我一直在学习linux运维,对于python也是接触不久,所以代码写的并不是很规范简洁. 前段时间一个同学找我一起做一个自动化运维平台,我对pytho ...

  6. Python 实现远程服务器批量执行命令

    paramiko 远程控制介绍 Python paramiko是一个相当好用的远程登录模块,采用ssh协议,可以实现linux服务器的ssh远程登录.首先来看一个简单的例子 import parami ...

  7. python之psutil模块(获取系统性能数据)

    psutil模块 1.介绍 psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等) ...

  8. Webpack执行命令参数详解

    一.概述前面的章节我们讲解了webpack的安装.webpack.config.js的 基本配置.webpack执行命名以及require方法的使用,不 知道大家有没有发现,当我们每次修改或者新增一个 ...

  9. python封装configparser模块获取conf.ini值

    configparser模块是python自带的从文件中获取固定格式参数的模块,因为是python只带的,大家用的应该很多,我觉得这个参数模块比较灵活,添加参数.修改参数.读取参数等都有对应的参数供用 ...

随机推荐

  1. MVC+EF 入门教程(四)

    一.前言 写了那么久,那么现在给大家看效果了 二.效果展示 点击创建Blog 显示 编辑 编辑成功,是不是很酷. 删除 终于完成了,准备睡觉!虽然有很多不足的地方,我会慢慢的去改的.感谢累了一天的自己 ...

  2. 为什么覆写equals()方法的时候总是要覆写hashcode()?

    要回答这个问题,我们应该先认识一下obj中的equals和hascode方法 1.equals()方法在obj中定义如下: public boolean equals(Object obj) { re ...

  3. IEEE1588 verision2 报文介绍

    PTP报文 PTP verision2报文是由 报头,主体 和 报尾 (header, body, and suffix)组成,报尾长度可能为0. PTP verision2报文在verision1的 ...

  4. OC学习13——Foundation框架中的集合

    OC集合类是一些非常有用的工具类,它可以用于存储多个数量不等的对象,并可以实现常用的数据结构(栈.队列等),此外,OC集合还可用于保存具有映射关系的关联数组.OC的集合大致可以分为:NSArray.N ...

  5. xamarin android布局

    xamarin android布局练习(1) xamarin android布局练习,基础非常重要,首先要学习的就是android的布局练习,xamarin也一样,做了几个xamarin androi ...

  6. 关于PLC

    学电气的一方面是单片机,一方面是PLC,,,,常常看到说选择比努力更重要,,单片机都很熟悉了,我就来介绍一下PLC..... 然后呢我先吹吹牛,,,目的是让大家相信我介绍的PLC绝对是亲身体验.... ...

  7. Who's in the Middle

    FJ is surveying his herd to find the most average cow. He wants to know how much milk this 'median' ...

  8. 多线程下QAxObject指针为NULL的解决办法

    项目中需要对Excel进行操作,把数据中的数据写入到Excel文件中.在数据量大的情况下,操作Excel是一件费时的操作. 但是执行到下列代码时就会出现空指针的情况: QAxObject *excel ...

  9. [摘抄]VC6.0移植到VS2008(vs2005)后的错误总结(未全部验证)

    ============================================================================================= 201405 ...

  10. ValueError: too many values to unpack (expected 2)

    记录下总是码错的地方 for key,value in final_table:#final_table is a dict 然后报错 File "./count_co_Mty_read_n ...