python 获取命令行参数

来源:互联网 发布:centos 集成环境 编辑:程序博客网 时间:2024/06/05 00:34

最近因工作需要使用Python写个脚本,用到了获取命令行参数,这里顺便总结下做个笔记,下次用到过来瞅瞅就方便的多了

import sysimport getoptdef 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,ccaa,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


0 0