Python的getopts 使用

import getopt
import sys
def usage():
print('''
this is help message
-h --help show help info
-i --input the input file or directory
-g --grep grep words
-t --time modify time
-v --verbose show verbose information
''')
pass
def main():
try:
opts,args=getopt.getopt(sys.argv[1:],"hi:g:t:v",["help","input=","grep=","time=","verbose"])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
inputinfo="null"
grep="null"
time="null"
verbose=False
for o,a in opts:
if o in ("-v","--verbose"):
verbose=True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-i","--input"):
inputinfo=a
elif o in ("-g","--grep"):
grep=a
elif o in ("-t","--time"):
time=a
else:
usage()
print("verbose="+str(verbose))
print("input="+inputinfo)
print("grep="+grep)
print("time="+time)
print(args)
print(opts)
if __name__=='__main__':
main()

原文地址:https://www.cnblogs.com/dlutxm/p/2997456.html