Comment traiter les messages d'erreur générés python mon propre chemin?
Question
Pour un code comme suit,
opts, args = getopt.getopt(sys.argv[1:], "c:", ... for o,v in opts: ... elif o in ("-c", "--%s" % checkString): kCheckOnly = True clientTemp = v
Si je ne donne pas le paramètre après l'-c, je reçois des messages d'erreur comme suit.
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
Est-il possible d'attraper cette erreur, et le processus pour imprimer quelque chose comme ça? Il semble que tout envelopper le code try / except ne fonctionne pas.
ERROR: You forgot to give the file name after -c option
La solution
Vous pouvez prendre getopt.GetoptError et cochez la case 'opt' et 'msg' vous les attributs:
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)
Autres conseils
la réponse correcte est d'utiliser le module OptionParser au lieu d'essayer de « rouler votre propre ».
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow