python之分割参数getopt
import sys
import getopt
def usage():
print("Usage:%s [-a|-o|-c] [--help|--output] args...." %Dsys.argv[0])
if "__main__" == __name__:
#lsArgs = [""]
try:
opts,args = getopt.getopt(sys.argv[1:], "ao:c", ["help", "output="])
print("============ opts ==================")
print(opts)
print("============ args ==================")
print(args)
#check all param
for opt,arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit(1)
elif opt in ("-t", "--test"):
print("for test option")
else:
print("%s ==> %s" %(opt, arg))
except getopt.GetoptError:
print("getopt error!")
usage()
sys.exit(1)
运行结果:
$ ./test_getopt.py -a -oaaa -caa --output=out file1 t file2 -d
============ opts ==================
[('-a', ''), ('-o', 'aaa'), ('-c', ''), ('-a', ''), ('-a', ''), ('--output', 'out')]
============ args ==================
['file1', 't', 'file2', '-d']
-a ==>
-o ==> aaa
-c ==>
-a ==>
-a ==>
--output ==> out
语音朗读: