最近因工作需要使用Python写个脚本,用到了获取命令行参数,这里顺便总结下做个笔记,下次用到过来瞅瞅就方便的多了
import sys
import getopt
def usage():
print ("sys.argv[0]: '-a aa -b bb -c cc'")
print ("sys.argv[0]: ' -h'")
def db_get_args():
try:
opts,args = getopt.getopt(sys.argv[1:], "ha:b:c:")
except getopt.GetoptError,err:
print str(err)
usage()
sys.exit(1)
if len(opts) == 3:
for op,value in opts:
if(op == "-h"):
usage()
sys.exit(1)
elif(op == "-a"):
aa = value
elif(op == "-b"):
bb = value
elif(op == "-c"):
cc = value
else:
usage()
sys.exit(1)
else:
usage()
sys.exit(1)
return aa,bb,cc
aa,bb,cc = db_get_args()
print aa,bb,cc
假如脚本名为getargs.py
执行脚本python getargs.py -a "hello" -b " world" -c "I'm comming"
则执行结果为
hello world I'm comming