How to print the full traceback without halting the program?
Quando non si vuole fermare il programma su un errore, è necessario gestire tale errore con un try/tranne:
try:
do_something_that_might_error()
except Exception as error:
handle_the_error(error)
Per estrarre il pieno traceback, useremo il modulo traceback
dalla libreria standard:
import traceback
E per creare uno stacktrace decentemente complicato per dimostrare che si ottiene il pieno stacktrace:
def raise_error():
raise RuntimeError('something bad happened!')
def do_something_that_might_error():
raise_error()
stampa
Per stampa traceback completo, utilizzare il metodo traceback.print_exc
:
try:
do_something_that_might_error()
except Exception as error:
traceback.print_exc()
che stampa:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
Meglio di stampa, la registrazione:
Tuttavia, una procedura consigliata è quella di impostare il registratore per il modulo. Si conosce il nome del modulo ed essere in grado di modificare i livelli di (tra gli altri attributi, come ad esempio i gestori)
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
In questo caso, si desidera la funzione logger.exception
invece:
try:
do_something_that_might_error()
except Exception as error:
logger.exception(error)
che registra:
ERROR:__main__:something bad happened!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
O forse si desidera solo la stringa, in questo caso, si desidera che la funzione traceback.format_exc
invece:
try:
do_something_that_might_error()
except Exception as error:
logger.debug(traceback.format_exc())
che registra:
DEBUG:__main__:Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
Conclusione
E per tutte e tre le opzioni, che vediamo noi ottenere lo stesso risultato quando abbiamo un errore:
>>> do_something_that_might_error()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
Perché non usare semplicemente 'traceback.print_exc()'? –
Voglio la stringa, mi fa piacere volting mi ha mostrato il metodo ('format_exc()') per ottenere la stringa :) –
@FrozenFlame perché potresti voler loggare te stesso prima di lanciarlo di nuovo – casraf