def main(): try: bar('0') except Exception as e: logging.exception(e)
main() print('END')
同样是出错,但程序打印完错误信息后会继续执行,并正常退出:
1 2 3 4 5 6 7 8 9 10 11
$ python3 err_logging.py ERROR:root:division by zero Traceback (most recent call last): File "err_logging.py", line 13, in main bar('0') File "err_logging.py", line 9, in bar return foo(s) * 2 File "err_logging.py", line 6, in foo return 10 / int(s) ZeroDivisionError: division by zero END
logging不会抛出错误, 而且可以输出到文件:
1 2 3 4 5 6
import logging
s = '0' n = int(s) logging.info('n = %d' % n) print(10 / n)
$ python err.py > /Users/michael/Github/learn-python3/samples/debug/err.py(7)<module>() -> print(10 / n) (Pdb) p n 0 (Pdb) c Traceback (most recent call last): File "err.py", line 7, in <module> print(10 / n) ZeroDivisionError: division by zero