对于一些代码如下,
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
答案 0 :(得分: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)
答案 1 :(得分:3)
正确答案是使用OptionParser模块而不是尝试“自己动手”。