2

对于如下一些代码,

    opts, args = getopt.getopt(sys.argv[1:], "c:", ...
    对于 opts 中的 o,v:
...
        elif o in ("-c", "--%s" % checkString):
            kCheckOnly = 真
            客户端温度 = v

如果我在 -c 之后没有给出参数,我会收到如下错误消息。

回溯(最近一次通话最后):
  文件“niFpgaTimingViolationMain.py”,第 100 行,在
    opts, args = getopt.getopt(sys.argv[1:], "hdc:t:",[helpString, debugString, checkString, twxString])
  文件“/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getopt.py”,第 91 行,在 getopt
    opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
  文件“/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getopt.py”,第 195 行,在 do_shorts
    选择)
getopt.GetoptError:选项 -c 需要参数

有什么办法可以捕捉到这个错误,并处理它来打印这样的东西?似乎仅将代码包装在 try/except 中是行不通的。

错误:您忘记在 -c 选项后提供文件名

4

2 回答 2

3

您可以捕获 getopt.GetoptError 并自己检查 'opt' 和 'msg' 属性:

尝试:
    opts, args = getopt.getopt(sys.argv[1:], "c:", ...
除了 getopt.GetoptError,e:
    如果 e.msg 中的 e.opt == 'c' 和 '需要参数':
        print >>sys.stderr, '错误:您忘记在 -c 选项后提供文件名'
        系统退出(-1)
于 2010-04-06T14:56:22.737 回答
3

正确的答案是使用 OptionParser 模块而不是尝试“自己动手”。

于 2010-04-06T14:58:24.697 回答