python的OptParser在解析的時候若是遇到異常會exit()。python
源碼:ide
1570 def exit(self, status=0, msg=None): 1571 if msg: 1572 sys.stderr.write(msg) 1573 sys.exit(status) 1574 1575 def error(self, msg): 1576 """error(msg : string) 1577 1578 Print a usage message incorporating 'msg' to stderr and exit. 1579 If you override this in a subclass, it should not return -- it 1580 should either exit or raise an exception. 1581 """ 1582 self.print_usage(sys.stderr) 1583 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
能夠經過派生和重載改變error行爲。this
82 class OptionParsingError(RuntimeError): 83 def __init__(self,msg): 84 self.msg = msg 85 86 class OptionParsingExit(Exception): 87 def __init__(self,status,msg): 88 self.msg=msg 89 self.status=status 90 91 class CMTOptionParser(optparse.OptionParser): 92 def error(self,msg): 93 raise OptionParsingError(msg) 94 95 def exit(self, status=0, msg=None): 96 raise OptionParsingExit(status,msg)