2010-04-06 20 views
2

对于一些代码如下, 如何以我自己的方式处理python生成的错误消息?

 
    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/wrap中包装代码不起作用。

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

+0

try-except子句不能正确工作吗? – SilentGhost 2010-04-06 15:00:34

+0

我弄错了,jemfinch给出了正确的例子。 – prosseek 2010-04-06 15:24:57

回答

3

你能赶上getopt.GetoptError并选中“选择”和“味精”的属性自己:

 
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) 
3

正确的答案是使用,而不是试图“辊OptionParser模块你自己”。

相关问题