import getopt import sys # -f: 代表当前参数有值 对应长参数为 filename= opts, args = getopt.getopt( sys.argv[1:], '-h-f:-v', ['help', 'filename=', 'version']) for opt_name, opt_value in opts: if opt_name in ('-h', '--help'): print("[*] Help info") exit() if opt_name in ('-v', '--version'): print("[*] Version is 0.01 ") exit() if opt_name in ('-f', '--filename'): fileName = opt_value print("[*] Filename is ", fileName) # do something exit()
# PS G:\Python\getoptdemo> python test.py --filename='test' # [*] Filename is test # PS G:\Python\getoptdemo> python test.py -f test # [*] Filename is test # PS G:\Python\getoptdemo> python test.py --version # [*] Version is 0.01 # PS G:\Python\getoptdemo> python test.py -v # [*] Version is 0.01 # PS G:\Python\getoptdemo>