getopt模块用于抽出命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式。
getopt函数的格式是getopt.getopt ( [命令行参数列表], "短选项", [长选项列表] )
短选项名后的冒号(:)表示该选项必须有附加的参数。
长选项名后的等号(=)表示该选项必须有附加的参数。
返回opts和args。
opts是一个参数选项及其value的元组( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args是一个除去有用参数外其他的命令行输入 ( 'a', 'b' )
然后遍历opts便可以获取所有的命令行选项及其对应参数了。
使用字典接受命令行的输入,然后再传送字典,可以使得命令行参数的接口更加健壮。
两个来自python2.5 Documentation的例子:
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
# ...
if __name__ == "__main__":
main()
python Documentation中也给出了getopt的典型使用方法:
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
# ...
if __name__ == "__main__":
main()
下面一段程序演示了在getopt下使用Usage()函数、参数字典(默认参数)、短选项、长选项等。
import os
import os.path
import sys
import getopt
def usage():
print '''
py price.py [option][value]...
-h or --help
-w or --wordattr-file="wordattr文件"
-s or --sflog-pricefile="sflog的价格变化文件"
-t or --tmpdir="临时文件的保存目录,默认为./"
-o or --outputfile="完整信息的保存文件,如果不指定,则输出到stdout"
-a or --wordattr-Complement="较新的wordattr去补全信息,缺省为Null,则丢失新广告的信息"
'''
return 0
if ( len( sys.argv ) == 1 ):
print '-h or --help for detail'
sys.exit(1)
shortargs = 'hw:s:t:o:a:'
longargs = ['help', 'wordattr=', 'sflog-pricefile=', 'tmpdir=', 'outputfile=', 'wordattr-Complement=']
opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )
if args:
print '-h or --help for detail'
sys.exit(1)
paramdict = {'tmpdir':os.path.abspath(os.curdir), 'outputfile':sys.stdout, 'newwordattr':None }
for opt,val in opts:
if opt in ( '-h', '--help' ):
usage()
continue
if opt in ( '-w', '--wordattr' ):
paramdict['wordattr'] = val
continue
if opt in ( '-s', '--sflog-pricefile' ):
paramdict['pricefile'] = val
continue
if opt in ( '-t', '--tmpdir' ):
paramdict['tmpdir'] = val
continue
if opt in ( '-o', '--outputfile' ):
try:
paramdict['outputfile'] = open(val,'w')
except Exception,e:
#ul_log.write(ul_log.fatal,'%s,%s,@line=%d,@file=%s' \
#%(type(e),str(e),sys._getframe().f_lineno,sys._getframe().f_code.co_filename))
sys.exit(1)
continue
if opt in ( '-a', '--wordattr-Complement' ):
paramdict['newwordattr'] = val
continue
2. 使用optparser模块处理Unix模式的命令行选项:
optparser模块非常的强大,完全体现了python的“如此简单,如此强大”的特性。
import optparse
def getConfig(ini):
import ConfigParser
try:
cfg = ConfigParser.ConfigParser()
cfg.readfp(open(ini))
print cfg.sections()
except:
pass
if __name__=='__main__':
parser = optparse.OptionParser()
parser.add_option(
"-i",
"--ini",
dest="ini",
default="config.ini",
help="read config from INI file",
metavar="INI"
)
parser.add_option(
"-f",
"--file",
dest="filename",
help="write report to FILE",
metavar="FILE"
)
parser.add_option(
"-q",
"--quiet",
dest="verbose",
action="store_false",
default=True,
help="don't print status messages to stdout"
)
(options, args) = parser.parse_args()
getConfig(options.ini)
print args
http://www.cnblogs.com/lovemo1314/archive/2012/10/16/2725589.html