美文网首页python hack
python解析获取到的命令行参数/getopt()函数使用

python解析获取到的命令行参数/getopt()函数使用

作者: 闭眼就能看得见 | 来源:发表于2019-01-19 17:15 被阅读0次

    getopt()函数

    作用

    • 解析获取到的命令行参数,一般用来解析sys.argv

    使用

    • getopt()函数为getopt模块内置函数。需导入getopt模块
    • opts,args = getopt.getopt(args,shortopts,longopts)
    • args是要解析的参数列表。用户命令行参数列表一般为sys.argv[1:]
    • shortopts:单个字符的短参数,若该参数后加,表示该参数是有值的。
    • longopts:多个字符的长参数,若该参数后加=,表示该参数是有值的。
    • 返回值是一个元组由两个列表组成,opts是由分别匹配到的命令行参数和对应值组成的元组构成,args是由没有匹配到的值构成
    • 使用for opt,value in opts 遍历匹配到的命令行参数,用if判断执行相应功能

    例1

      1 import sys
      2 import getopt
      3 opts,args = getopt.getopt(sys.argv[1:],"hl:s:",["test=","mh"])
      4 print (opts)
      5 print (args)
    

    运行演示

    m@m-virtual-machine:~$ python3 test.py -h
    [('-h', '')]
    []
    m@m-virtual-machine:~$ python3 test.py -h a
    [('-h', '')]
    ['a']
    m@m-virtual-machine:~$ python3 test.py -h -s a
    [('-h', ''), ('-s', 'a')]
    []
    m@m-virtual-machine:~$ python3 test.py -h -s a -l b
    [('-h', ''), ('-s', 'a'), ('-l', 'b')]
    []
    m@m-virtual-machine:~$ python3 test.py -h -s a -l b --test=c
    [('-h', ''), ('-s', 'a'), ('-l', 'b'), ('--test', 'c')]
    []
    m@m-virtual-machine:~$ python3 test.py -h -s a -l b --test=c --mh
    [('-h', ''), ('-s', 'a'), ('-l', 'b'), ('--test', 'c'), ('--mh', '')]
    []
    

    例2

      1 import sys
      2 import getopt
      3 opts,args = getopt.getopt(sys.argv[1:],"a:b:",["help"])
      4 print (opts)
      5 print (args)
      6 for opt,value in opts:
      7     if opt == '--help':
      8         print("使用说明:")
      9         print("-a ip -p port")
     10         print("--help 获取使用说明")
    

    运行演示

    m@m-virtual-machine:~$ python3 test.py --help
    [('--help', '')]
    []
    使用说明:
    -a ip -p port
    --help 获取使用说明
    

    相关文章

      网友评论

        本文标题:python解析获取到的命令行参数/getopt()函数使用

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