python的命令解析getopt.getopt()函数分析
2011-08-12 14:13
573 查看
【转自http://hi.baidu.com/javalang/blog/category/Python】
可以参考http://docs.python.org/lib/module-getopt.html
# -*- coding: cp936 -*-
import getopt
import sys
def usage():
print '''Help Information:
-h: Show help information
-xValue:
...'''
if __name__=='__main__':
#set default values
x=1
y='y'
try:
print sys.argv[1:]
opts,args=getopt.getopt(sys.argv[1:],'hx:y:d')
#opts 是带-选项的参数
#args 是没有选项的参数
print opts
print args
#h表示使用-h,h选项没有对应的值
#x:表示你要使用-xValue,x选项必须有对应的值.
except getopt.GetoptError:
#打印帮助信息并退出
usage()
sys.exit(2)
#处理命令行参数
for o,a in opts:
if o=='-h':
usage()
sys.exit()
if o=='-x':
try:
x=x+int(a) #注意默认a为字符串
except ValueError:
print 'Invalid Value'
print x
if o=='-d':
print 'use -d'
if o=='-y':
y=y+a
运行结果:
getopt_example.py -x12 -y ss -d sdf s123
['-x12', '-y', 'ss', '-d', 'sdf', 's123']
[('-x', '12'), ('-y', 'ss'), ('-d', '')]
['sdf', 's123']
13
use -d
可以参考http://docs.python.org/lib/module-getopt.html
# -*- coding: cp936 -*-
import getopt
import sys
def usage():
print '''Help Information:
-h: Show help information
-xValue:
...'''
if __name__=='__main__':
#set default values
x=1
y='y'
try:
print sys.argv[1:]
opts,args=getopt.getopt(sys.argv[1:],'hx:y:d')
#opts 是带-选项的参数
#args 是没有选项的参数
print opts
print args
#h表示使用-h,h选项没有对应的值
#x:表示你要使用-xValue,x选项必须有对应的值.
except getopt.GetoptError:
#打印帮助信息并退出
usage()
sys.exit(2)
#处理命令行参数
for o,a in opts:
if o=='-h':
usage()
sys.exit()
if o=='-x':
try:
x=x+int(a) #注意默认a为字符串
except ValueError:
print 'Invalid Value'
print x
if o=='-d':
print 'use -d'
if o=='-y':
y=y+a
运行结果:
getopt_example.py -x12 -y ss -d sdf s123
['-x12', '-y', 'ss', '-d', 'sdf', 's123']
[('-x', '12'), ('-y', 'ss'), ('-d', '')]
['sdf', 's123']
13
use -d
相关文章推荐
- PYTHON的函数对参数解析分析
- linux bash shell 中getopts 命令 和 python 中 getopt 函数的比较总结
- linux bash shell 中getopts 命令 和 python 中 getopt 函数的比较总结
- linux学习之命令参数解析——getopt()函数
- Linux命令选项及参数解析 getopt() getopt_long() 函数
- python的函数对参数解析分析
- python 实现远程主机执行命令函数
- Python中的getopt函数使用详解
- Python urllib模块与urlopen()函数解析偎
- python中的列表解析与函数参数*args **kwargs用法
- python/pandas/numpy数据分析(十)-函数, rank,重复索引
- Python封装shell命令实例分析
- 程序参数解析函数使用getopt_long()函数,改编自webbench
- 命令行程序选项解析函数—getopt
- Python数据分析模块 | pandas做数据分析(三):统计相关函数
- Python字典,函数,全局变量代码解析
- Learning Python:1. 生成器函数、列表解析与map,for循环的效率对比
- UiAutomator系列——Appium Android Bootstrap源码分析之命令解析执行(008)
- MySQL命令解析主要函数调用
- 简单分析Python中用fork()函数生成的子进程