2010-04-06 12 views
2

Pour un code comme suit, Comment traiter les messages d'erreur générés par python à ma manière?

 
    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 l'emballage du code dans try/except ne fonctionne pas.

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

+0

Comment la clause try-except ne fonctionne pas exactement? – SilentGhost

+0

J'ai eu un problème et jemfinch a donné le bon exemple. – prosseek

Répondre

3

Vous pouvez attraper getopt.GetoptError et cochez la case 'opt' et 'msg' vous attribue:

 
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

la bonne réponse est d'utiliser le module OptionParser au lieu d'essayer de « rouleau le tien".