如何自定义处理Python生成的错误消息?

2 投票
2 回答
785 浏览
提问于 2025-04-15 21:17

下面是一些代码,

    opts, args = getopt.getopt(sys.argv[1:], "c:", ...
    for o,v in opts:
...
        elif o in ("-c", "--%s" % checkString):
            kCheckOnly = True
            clientTemp = v

如果我在 -c 后面不提供参数,就会出现以下错误信息。

Traceback (most recent call last):
  File "niFpgaTimingViolationMain.py", line 100, in 
    opts, args = getopt.getopt(sys.argv[1:], "hdc:t:",[helpString, debugString, checkString, twxString])
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getopt.py", line 91, in getopt
    opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getopt.py", line 195, in do_shorts
    opt)
getopt.GetoptError: option -c requires argument

有没有办法捕捉到这个错误,并处理它,让它打印出类似这样的信息?看起来仅仅把代码放在 try/except 里并不能解决这个问题。

ERROR: You forgot to give the file name after -c option

2 个回答

3

正确的做法是使用OptionParser模块,而不是自己去实现一个。

3

你可以捕捉到 getopt.GetoptError 这个错误,然后自己检查它的 'opt' 和 'msg' 属性:

try:
    opts, args = getopt.getopt(sys.argv[1:], "c:", ...
except getopt.GetoptError, e:
    if e.opt == 'c' and 'requires argument' in e.msg:
        print >>sys.stderr, 'ERROR: You forgot to give the file name after -c option'
        sys.exit(-1)

撰写回答