Python3 中getopt用法

2021-04-27  本文已影响0人  tafanfly

getopt

该模块是专门用来处理命令行参数的
函数:opts, args = getopt(args, shortopts, longopts = [])
参数:

返回:

import sys
import getopt


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hi:', ['help', 'input='])
        print (opts, args)
    except getopt.GetoptError as e:
        print ('Got a eror and exit, error is %s' % str(e))

测试结果如下:

$ python getopt_test.py
[] []
$ python getopt_test.py value1 value2
[] ['value1', 'value2']
$ python getopt_test.py -h
[('-h', '')] []
$ python getopt_test.py -h 1
[('-h', '')] ['1']
$ python getopt_test.py -h -p
Got a eror and exit, error is option -p not recognized
$ python getopt_test.py -i
Got a eror and exit, error is option -i requires argument
$ python getopt_test.py -i 1
[('-i', '1')] []
$ python getopt_test.py -i -p
[('-i', '-p')] []
$ python getopt_test.py -a
Got a eror and exit, error is option -a not recognized
$ python getopt_test.py --help
[('--help', '')] []

$ python getopt_test.py --help 1
[('--help', '')] ['1']

$ python getopt_test.py --help --ls
Got a eror and exit, error is option --ls not recognized

$ python getopt_test.py --help --input
Got a eror and exit, error is option --input requires argument

$ python getopt_test.py --help --input 2
[('--help', ''), ('--input', '2')] []

$ python getopt_test.py --help --input 2 3
[('--help', ''), ('--input', '2')] ['3']
$ python getopt_test.py -h -i 1 --help --input 2 3
[('-h', ''), ('-i', '1'), ('--help', ''), ('--input', '2')] ['3']
上一篇 下一篇

猜你喜欢

热点阅读