Python之getopt模块
1、getopt——C风格命令行解析
http://docs.python.org/2.7/library/getopt.html#module-getopt
getopt.getopt(args, options[, long_options])
先引入一个例子:
>>> import getopt
>>>
>>> args = "-a -b -cfoo -d bar a1 a2".split() #将输入的参数转换成一个列表,通常在实例应用中args = sys.argv[1:]
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist,args = getopt.getopt(args,'abc:d:') #abc:d:,说明a和b只是是否有该选项,但是后面不跟值,而c和d不同,后面是有值的,故以冒号(:)区分
>>>
>>> optlist #获取到参数以及对应的值
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args #-d后续只跟一个值,故a1和a2当做参数
['a1', 'a2']
上面的例子是短选项模式,下面再举个长选项模式的例子:
>>> import getopt
>>>
>>> s = "--condition=foo --testing --output-file abc.def -a foo -x a1 a2" #长选项和短选项结合,-x和-a是短选项,其他都是长选项
>>>
>>> args = s.split()
>>>
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-a', 'foo', '-x', 'a1', 'a2']
>>>
>>> optlist,args = getopt.getopt(args,'x','a',['condition=','output-file=','testing'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: getopt() takes at most 3 arguments (4 given)
>>>
>>> optlist,args = getopt.getopt(args,'xa:',['condition=','output-file=','testing']) #getopt.getopt()函数接受三个参数,第一个是所有参数输入,第二个是短选项,第三个是长选项
>>>
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-a', 'foo'), ('-x', '')]
>>> args
['a1', 'a2']
getopt模块用于抽出命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式。
getopt函数的格式是getopt.getopt ( [命令行参数列表], "短选项", [长选项列表] )
返回两个参数optlist,args
optlist是一个参数以及对应的vaule构成的元组
args是除了参数外其他的命令输入
然后遍历optlist便可以获取所有的命令行以及对应参数:
>>> for opt,val in optlist:
... if opt in ('-a','--a_long'):
... pass
... if opt in (xxx)
使用字典接受命令行的输入,然后再传送字典,可以使得命令行参数的接口更加健壮。
python文档中给出使用方法:
#!/usr/bin/env python26
#-*- coding:utf-8 -*- import getopt
import sys
def usage():
help_msg = '''Usage:./test_opt.y [option] [value]...
-h --help show help
-o --output output file
-v verbose''' print help_msg def main():
if len(sys.argv) == 1:
usage()
sys.exit()
try:
opts,args = getopt.getopt(sys.argv[1:],'ho:v',["help","output="])
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
except Exception,e:
print e output = None
verbose = False for opt,arg in opts:
if opt == "-v":
verbose = True
elif opt in ("-h","--help"):
usage()
sys.exit()
elif opt in ("-o","--output"):
output = arg
else:
assert False,"unhandled option"
if __name__ == "__main__":
main()
2、argparse——python2.7中新添加的
http://docs.python.org/2.7/library/argparse.html#module-argparse
http://www.cnblogs.com/lovemo1314/archive/2012/10/16/2725589.html
Python之getopt模块的更多相关文章
- python通过getopt模块获取执行命令参数
python脚本和shell脚本一样可以获取命令行的参数,根据不同的参数,执行不同的逻辑处理. 通常我们可以通过getopt模块获得不同的执行命令和参数. 下面我通过新建一个test.py的脚本解释下 ...
- python getopt模块使用方法
python中 getopt 模块,是专门用来处理命令行参数的 getop标准格式: 函数getopt(args, shortopts, longopts = []) shortopts 是短参数 ...
- 【转】getopt模块,实现获取命令行参数
python中 getopt 模块,该模块是专门用来处理命令行参数的 函数getopt(args, shortopts, longopts = []) 参数args一般是sys.argv[1:],sh ...
- (转载)python: getopt的使用;
注: 该文转载于https://blog.csdn.net/tianzhu123/article/details/7655499python中 getopt 模块, 该模块是专门用来处理命令行参数的 ...
- [转]Python 命令行参数和getopt模块详解
FROM : http://www.tuicool.com/articles/jaqQvq 有时候我们需要写一些脚本处理一些任务,这时候往往需要提供一些命令行参数,根据不同参数进行不同的处理,在Pyt ...
- Python 命令行参数和getopt模块详解
有时候我们需要写一些脚本处理一些任务,这时候往往需要提供一些命令行参数,根据不同参数进行不同的处理,在Python里,命令行的参数和C语言很类似(因为标准Python是用C语言实现的).在C语言里,m ...
- Python getopt 模块
Python getopt 模块 getopt模块,是配合sys.argv使用的一个扩展.他可以接收终端的参数.格式扩展为“-n” 或 “--n”两种类型,下面是具体解释. 使用 improt get ...
- Python 中的 getopt 模块
sys 模块:可以得到用户在命令行输入的参数 getopt模块:专门用来处理输入的命令行参数 用户在命令行中输入参数,sys模块得到该参数,getopt模块处理该参数 sys模块: import sy ...
- python获取命令行传参的两种种常用方法argparse解析getopt 模块解析
方法一:argparse解析 #!/usr/bin/env python3 # -*- coding:utf-8 -*- # @Time: 2020/5/20 10:38 # @Author:zhan ...
随机推荐
- Python接口自动化——soap协议传参的类型是ns0类型的要创建工厂方法纪要
1:在Python接口自动化中,对于soap协议的xml的请求我们可以使用Suds Client来实现,其soap协议传参的类型基本上是有2种: 第一种是传参,不需要再创建啥, 第二种就是ns0类型的 ...
- sqlDependency监控数据库数据变化,自动通知
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- 根据Dockerfile创建docker dotnet coer 镜像
那我们先来看看Dockerfile文件内容,注意这个文件是没后缀名的. #依赖原始的镜像,因为我们是要创建dotnet coer镜像,所以我就用了官方给的镜像[microsoft/dotnet:lat ...
- Android onSaveInstanceState和onRestoreInstanceState()
首先来介绍onSaveInstanceState() 和 onRestoreInstanceState() .关于这两个方法,一些朋友可能在Android开发过程中很少用到,但在有时候掌握其用法会帮我 ...
- http服务详解(1)——一次完整的http服务请求处理过程
前言:要熟练掌握一个服务,首先需要非常了解这个服务的工作过程,这篇就详细解释了http服务的请求处理过程. 一次完整的http请求处理过程 (1)流程图 (2)过程详解 0.DNS域名解析:递归查询. ...
- win10 UWP GET Post
win10 应用应该是要有访问网络,网络现在最多的是使用GET,Post,简单的使用,可以用网络的数据:获得博客的访问量. 在使用网络,我们需要设置Package.appxmanifest 网络请求使 ...
- Java调度线程池ScheduledThreadPoolExecutor源码分析
最近新接手的项目里大量使用了ScheduledThreadPoolExecutor类去执行一些定时任务,之前一直没有机会研究这个类的源码,这次趁着机会好好研读一下. 该类主要还是基于ThreadPoo ...
- APP崩溃提示:This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
崩溃输出日志 2017-08-29 14:53:47.332368+0800 HuiDaiKe[2373:1135604] This application is modifying the auto ...
- Mybatis Mapper.xml 需要查询返回List<String>
当需要查询返回 List<String> <select id="getByIds" parameterType="java.lang.String&q ...
- ArrayList 源码(基于Java1.8)
ArrayList 源码 ArrayList 基于数组实现,也就是类对变量 Object[]系列操作,封装为常用的add,remove,indexOf, contains本质是通过 size 计数器对 ...