方法1:
Python有一个类可以专门处理命令行参数,先看代码:
#!/usr/bin/env python#encoding: utf-8fromoptparseimportOptionParser
parser= OptionParser(usage="%PRog [options]")
parser.add_option("-m","--machine",action="store",type="string",dest="machine",help="the machine to be check")
(options,args)=parser.parse_args()ifoptions.machine:printoptions.machine
第一行用来初始化,
-m 为参数简写,—machine 为完整参数 store意思为将该参数存储, type为存储类型。dest为存储至哪个变量,默认为完整参数名,help为帮助时显示的内容
方法2:
使用getopt模块来解析
importsysimportgetoptdefTestGetOpt():try:
opts, args= getopt.getopt(sys.argv[1:],'d:f:h',['days=','files=','help'])exceptgetopt.GetoptError:
usage()
sys.exit()print(opts)print(args)foro, ainopts:ifoin("-h","--help"):
usage()
sys.exit()elifoin("-d","--days"):
day=aelifoin("-f","--files"):
files=aprint(day)print(files)
参见:http://blog.csdn.net/lwnylslwnyls/article/details/8199454