代码之家  ›  专栏  ›  技术社区  ›  Hind Forsum

python getopt抛出getopterror选项——mode不能有参数

  •  0
  • Hind Forsum  · 技术社区  · 6 年前

    当我指定命令行选项时,getopt似乎不起作用,抛出异常,这个名为o.py的文件:

    import getopt
    import sys
    opts,args = getopt.getopt(sys.argv[1:], "m:p:", ['mode', 'perf'])
    for opt_name,opt_value in opts:
        if opt_name in ('--mode'):
            print opt_name
            continue
        if opt_name in ('--perf'):
            print opt_name
            continue
    

    然后在以下情况下出现运行时异常:

    python o.py --mode=a
    Traceback (most recent call last):
    File "o.py", line 3, in <module>
        opts,args = getopt.getopt(sys.argv[1:], "m:p:", ['mode', 'perf'])
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/getopt.py", line 88, in getopt
        opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/getopt.py", line 159, in do_longs
        raise GetoptError('option --%s must not have an argument' % opt, opt)
    getopt.GetoptError: option --mode must not have an argument
    opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
    

    文件“/library/frameworks/python.framework/versions/2.7/lib/python2.7/getopt.py”,第159行 raise getopterror('option--%s不能有参数%opt,opt) getopt.getopterror:option--mode不能有参数

    那我哪里出错了,怎么解决呢?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Ondrej K.    6 年前

    长选项名称缺少尾随 = . 见 docs ,即:

    longopts(如果指定)必须是一个字符串列表,其中包含应支持的long选项的名称。选项名称中不应包含前导'--'字符。 需要参数的长选项后面应该跟一个等号('=')

    即。

    opts,args = getopt.getopt(sys.argv[1:], "m:p:", ['mode=', 'perf='])