2020-06-06 getopt模块处理命令行参数

2020-06-06  本文已影响0人  菜菜笛

opts, args = getopt.getopt(args, shortopts, longopts=[])
opts用于接收有 - 或 -- 的参数,是一个元素为元组的列表,元组内容为(参数键,参数值)
返回值args用于接收没有有 - 或 -- 的参数,是一个元素为字符串的列表
参数args要解析的命令行参数列表,可以用sys.argv[1:]获取
shortopts定义短参数,比如'hvs:',冒号表示如果设置该选项,必须有附加的参数,否则就不附加参数。
longopts定义长参数,比如['help', 'version', 'step='],等号和上面的冒号意义相同
在没有找到参数列表,或选项的需要的参数为空时会触发异常Exception getopt.GetoptError

# what1.py
import getopt
import sys

try:
    opts, args = getopt.getopt(sys.argv[1:], 'hvs:', ['help', 'version', 'step='])
except getopt.GetoptError:
    print('参数错误')
    sys.exit(2)
print("opts", opts)
print("args", args)
for x in opts:
    print("x:", x)
for opt_name,opt_value in opts:
    print("opt_name,opt_value:", opt_name, opt_value)
    if opt_name == ("-h", "--help"):
         pass
    elif opt_name in ("-s", "--step"):
         pass
    elif opt_name in ("-o", "--ofile"):
         pass
D:\PyCharm_WorkSpace\untitled>
D:\PyCharm_WorkSpace\untitled>python what1.py -h -v -s 1 a b c
opts [('-h', ''), ('-v', ''), ('-s', '1')]
args ['a', 'b', 'c']
x: ('-h', '')
x: ('-v', '')
x: ('-s', '1')
opt_name,opt_value: -h
opt_name,opt_value: -v
opt_name,opt_value: -s 1

D:\PyCharm_WorkSpace\untitled>python what1.py --help -version -step 1 a b c
参数错误

D:\PyCharm_WorkSpace\untitled>python what1.py --help --version --step 1 a b c
opts [('--help', ''), ('--version', ''), ('--step', '1')]
args ['a', 'b', 'c']
x: ('--help', '')
x: ('--version', '')
x: ('--step', '1')
opt_name,opt_value: --help
opt_name,opt_value: --version
opt_name,opt_value: --step 1

参考和感谢:
https://www.runoob.com/python/python-command-line-arguments.html
https://www.jianshu.com/p/a877e5b46b2d

上一篇 下一篇

猜你喜欢

热点阅读