开发者

How to process python generated error messages my own way?

For some code as follows,

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

If I don't give the parameter after the -c, I get the error messages as follows.

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

Is there any way to catch this error, and process it to print something like this? It seems that just wrapping the code in try/except doesn't work.

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


You can catch getopt.GetoptError and check the 'opt' and 'msg' attributes yourself:

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)


the correct answer is to use the OptionParser module instead of trying to "roll your own".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜