Wie Python erzeugte Fehlermeldungen meine eigene Art und Weise verarbeiten?
Frage
Für einige Code wie folgt,
opts, args = getopt.getopt(sys.argv[1:], "c:", ... for o,v in opts: ... elif o in ("-c", "--%s" % checkString): kCheckOnly = True clientTemp = v
Wenn ich nicht den Parameter nach dem -c geben, erhalte ich die Fehlermeldung wie folgt.
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
Gibt es eine Möglichkeit, diesen Fehler zu fangen und verarbeitet es etwas zu drucken? Es scheint, dass nur den Code in try Einwickeln / except nicht funktioniert.
ERROR: You forgot to give the file name after -c option
Lösung
Sie können getopt.GetoptError fangen und prüfen Sie die 'opt' und 'msg' Attribute selbst:
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)
Andere Tipps
die richtige Antwort ist, den OptionParser Modul zu verwenden, anstatt zu versuchen, „Ihre eigene Rolle“.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow