美文网首页
Python3 中getopt用法

Python3 中getopt用法

作者: tafanfly | 来源:发表于2021-04-27 09:54 被阅读0次

    getopt

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

    • args: 一般是sys.argv[1:]
    • shortopts: 短格式 (-) , 只表示开关状态时,即后面不带附加数值时,在分析串中写入选项字符。当选项后面要带一个附加数值时,在分析串中写入选项字符同时后面加一个:号 , 如"vc:"。
    • longopts:长格式(--) , 只表示开关状态时,即后面不带附加数值时,在队列中写入选项字符。当选项后面要带一个附加数值时,在队列中写入选项字符同时后面加一个=号 , 如["help", "log="] 。

    返回:

    • opts: 分析出的格式信息,是一个两元组的列表,即[(选项串1, 附加参数1), (选项串2, '')], 注意如果没有附加数值则为空字符串
    • args: 为不属于格式信息的剩余的命令行参数
    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))
    

    测试结果如下:

    • 不传任何参数, 返回两个空的list
    $ python getopt_test.py
    [] []
    
    • 不传带---的参数, opts是空的列表,args是两个入参的列表
    $ python getopt_test.py value1 value2
    [] ['value1', 'value2']
    
    • 输入含有-h的参数, 可以得知h后不接:, 表明-h不会去取值
    $ 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
    
    • 输入含有-i的参数, 可以得知i后接:, 表明-i一定会去取值
    $ 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']
    

    相关文章

      网友评论

          本文标题:Python3 中getopt用法

          本文链接:https://www.haomeiwen.com/subject/lhtfrltx.html