python日积月累学模块 getopt

getopt模块是获取和解析输入参数的模块
主要方法:
getopt(参数列表,选项,[长参数选项列表])
返回值 是一个list,list的项为(选项,值)的元组对
演示代码
# -*- coding: cp936 –*-
## @file demogetopt.py
## @author [email protected]
## @brief getopt模块演示程序
#############################################################
#import
#############################################################
import os, sys
import getopt
#############################################################
#global values
#############################################################
USAGE="""NAME:
demogetopt.py - getopt模块演示程序,对输入参数进行解析
SYNOPSIS:
python demogetopt.py [OPTION]... [FILE]...
DESCRIPTION:
Options and arguments:
-h, --help display this help and exit
-f, --file parse the full path of file
-t, --type type of parse method
"""
#############################################################
#static function
#############################################################
#############################################################
#class
#############################################################
############################# main ###########################
if __name__=="__main__":
## 参数解析
stattype = ""
objfile = ""
if len(sys.argv) < 2:
print USAGE
sys.exit(0)
try:
opts, args = getopt.getopt(sys.argv[1:], "ht:f:",["help","type=","file="])
except Exception, e:
print e
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
print USAGE
sys.exit(0)
elif opt in ("-t", "--type"):
stattype = arg
elif opt in ("-f", "--file"):
objfile = arg
else:
print "unknown options"
sys.exit(1)
print "-t/--type =",stattype
print "-f/--file =",objfile
##
#do something
##
sys.exit(0)
Tags: 

延伸阅读

最新评论

发表评论