for i in target: if i.startswith("-"): key.append(i)
for i in key: n = sys.argv.index(i) if i == '-h'or i == '--help': gethelp() #获取帮助,需要在前面定义函数 elif i == '-ex1'or i == '--example1': example1(sys.argv[n+1]) #同样是前面定义的函数,传入参数为命令的第二个参数 elif i == '-ex2'or i == '--example2': example2(sys.argv[n+1]) else: print(f'No such parm:{i}')
for i in target: if i.startswith("-"): key.append(i)
for i in key: n = sys.argv.index(i) if i == '-h'or i == '--help': gethelp() elif i in key_list: key_list[i](sys.argv[n+1]) else: print(f'No such parm:{i}')
for i in target: if i.startswith("-"): k = target.index(i)
for i in key: n = sys.argv.index(i) if i in key_list_0: key_list_0[i]() elif i in key_list_1: key_list_1[i](sys.argv[n+1]) else: print(f'No such parm:{i}')
target = sys.argv[1:] for i in target: if i.startswith("-"): k = target.index(i) key.append(i)
for i in key: n = sys.argv.index(i) if i in key_list_0: key_list_0[i]() if i in key_list_1: key_list_1[i](sys.argv[n+1]) elif i == '-ex3'or i == '--example3': ex3 == True ex3_i = n else: print(f'No such parm:{i}') if ex3: example3(sys.argv[ex3_i+1])
这样,在调用-ex3和--example3时,将会运行example3方法,不使用也不会报错
这里可能会出现问题:当只使用可选参数时,她将出现问题,我们这里给她做一个排除:
1 2 3 4 5 6 7 8 9
key = [] target = sys.argv[1:] for i in target: if i.startswith("-"): key.append(i) iflen(key) < 2: if key == '-o': print("Error:不可只调用可选参数") sys.exit(0)