python之getopt模块

在perl中,我们常使用Getopt::Std模块来传递命令行参数给程序,在python有类似模块getopt,介绍最重要方法getopt。
getopt.getopt(args, options[, long_options])
args为sys.argv[1:] 指:脚本后面的参数,sys.argv[0]指脚本本身
options为选项字母(以”-”开头),后面跟”:”,说明带有参数值
long_options为字符串list(以”–”开头),后面跟”=”,说明带有参数值

#!/usr/bin/python
import getopt
import sys
#函数有两个返回,opts为(option,value)的list,args是为未匹配的参数
opts, args = getopt.getopt(sys.argv[1:], "dh", ["start", "stop","restart","debug","help"]) 
print opts
print args
for o, a in opts:
        if o == "--start":
                print  "start..."
        elif o == "--stop":
                print "stop..."
        elif o == "restart":
                print "stop...start..."
        elif o in ("-d", "--debug"):
                print "debug..."
        elif o in ("-h","--help"):
                print "usage()..."
        else:
                assert False, "unhandled option"
$./para.py -d a
[('-d', '')]
['a']
 -debug

“dh”修改成”d:h”

opts, args = getopt.getopt(sys.argv[1:], "d:h", ["start", "stop","restart","debug","help"])
$./para.py -d a
[('-d', 'a')]
[]
 -debug

Post a Comment