当前位置:   article > 正文

Python 参数解析处理 getopt_python getopt 输入不匹配参数

python getopt 输入不匹配参数

使用Python库导入

import sys
import getopt
  • 1
  • 2

获取运行Python传入的参数

# 使用sys.argv获取到的参数第一个为脚本的名字,如果不是,执行就会报错
# 我们使用getopt解析是一般都会使用sys.argv[1:]过滤掉第一个参数, 即过滤掉脚本的名字
argv = sys.argv
  • 1
  • 2
  • 3

解析前说明

  • getopt定义
    def getopt(args, shortopts, longopts = [])
    
    • 1
  • getopt分析
    • 调用getopt函数,函数返回两个列表:opts和args,opts为分析出的格式信息,args为不属于格式信息中剩余的命令行参数
    • args 从名字上来看,这个是传入的参数,我们使用时一般传入的是sys.argv[1:],即执行python脚本时传入的过滤掉脚本名的参数内容
    • shortopts 使用短格式分析串。例如"-h",后面不加带附加参数,分析串中需要写上"h“或 “-h”,例如 “-o file”, 后面带有附加参数的情况,分析串中要写成”o:" 或者"-o:"
    • longopts 使用长格式分析串列表。例如"--help",后面不跟"=", 分析串列表中需要加入"["help"]", 例如 --output=out,后面带有"=",分析串列表中需要加入"[output=]"
    • 整个过程中调用的时候最好使用异常来包含,因为在分析中如果传入的shortopts,longopts值或者调用python脚本的参数顺序不对时会发生异常

使用getopt函数以及python调用时的注意事项

一.正常操作

  • getopt函数调用中传入的参数包含调用python脚本时传入的所有参数
    • Code
      import sys
      import getopt
      
      if __name__ == '__main__':
          opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
          print("opts: " + opts)
          print("args: " + args)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    • Output
      python test.py -h -o file --help --output=out file1 file2
      >>> [('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]
      >>> ['file1', 'file2']
      
      • 1
      • 2
      • 3
  • getopt函数调用中传入的参数比调用python脚本时传入的参数多
    • Code
      import  sys
        import gtopt
        if __name__ == '__main__':
            opts, args = getopt.getopt(sys.argv[1:], "hto:", ["help", "test", "output="])
            print(opts)
            print(args)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    • Output
      python test.py -h -o file --help --output=out file1 file2
      >>> [('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]
      >>> ['file1', 'file2']
      
      • 1
      • 2
      • 3

二.异常操作

  • 调用python脚本时输入带有-或者--类型的参数在getopt函数调用时没有写入

    • Code

      import sys
      import getopt
      
      if __name__ == '__main__':
          opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
          print("opts: " + opts)
          print("args: " + args)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    • Output

      会导致异常

      python test.py -h -t -o file --help --output=out file1 file2
      >>> Traceback (most recent call last):
      >>>   File "test.py", line 5, in <module>
      >>>     opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
      >>>   File "C:\Python37\lib\getopt.py", line 95, in getopt
      >>>     opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
      >>>   File "C:\Python37\lib\getopt.py", line 195, in do_shorts
      >>>     if short_has_arg(opt, shortopts):
      >>>   File "C:\Python37\lib\getopt.py", line 211, in short_has_arg
      >>>     raise GetoptError(_('option -%s not recognized') % opt, opt)
      >>> getopt.GetoptError: option -t not recognized
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
  • getopt函数调用中传入的参数和调用python脚本时传入的参数类型不匹配,例如脚本调用时传入的是"-o file", getopt函数调用时使用"o“而不是”o:"

    • Code

      import sys
      import getopt
      
      if __name__ == '__main__':
          opts, args = getopt.getopt(sys.argv[1:], "ho", ["help", "output="])
          print(opts)
          print(args)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    • Output

      打印出的opts和args的值不符合预期

      python test.py -h -o file --help --output=out file1 file2
      >>> [('-h', ''), ('-o', '')]
      >>> ['file', '--help', '--output=out', 'file1', 'file2']
      
      • 1
      • 2
      • 3
  • 调用python脚本时调用时带有-或者--类型的参数放到了其它类型参数之后

    • Code

      import sys
      import getopt
      
      if __name__ == '__main__':
          opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
          print(opts)
          print(args)
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    • Output

      打印出的opts和args的值不符合预期, "-o"参数未解析到

      python test.py -h --help --output=out file1 file2 -o file
      >>> [('-h', ''), ('--help', ''), ('--output', 'out')]
      >>> ['file1', 'file2', '-o', 'file']
      
      • 1
      • 2
      • 3

如何使用

  • 在使用getopt函数处理之后,会得到两个opts和args两个数组,我们可以通过for循环的方式来获取用户传入的值

    import sys
    import getopt
    
    if __name__ == '__main__':
        try:
            opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
            print(opts)
            print(args)
            for option, value in opts:
                print(f"option: {option}, value: {value}")
        except Exception as e:
            print(f"Error: {e}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    python test.py -h -o file --help --output=out file1 file2
    >>> [('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]
    >>> ['file1', 'file2']
    >>> option: -h, value:
    >>> option: -o, value: file
    >>> option: --help, value:
    >>> option: --output, value: out
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/811931
推荐阅读
相关标签
  

闽ICP备14008679号