python 獲取命令列引數
阿新 • • 發佈:2019-02-12
最近因工作需要使用Python寫個指令碼,用到了獲取命令列引數,這裡順便總結下做個筆記,下次用到過來瞅瞅就方便的多了
假如指令碼名為getargs.pyimport 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
執行指令碼python getargs.py -a "hello" -b " world" -c "I'm comming"
則執行結果為
hello world I'm comming