Python traceback模块的使用(抛异常、报错、输出错误)
生活随笔
收集整理的這篇文章主要介紹了
Python traceback模块的使用(抛异常、报错、输出错误)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#!/usr/bin/python
# -*- coding: UTF-8 -*-import tracebacktry:fh = open("testfile", "w")fh.write("這是一個測試文件,用于測試異常!!")#fh = open("testfile", "r")#print(fh.read())
except Exception as e: traceback.print_exc()try:#fh = open("testfile", "r")#print(fh.read())fh = open("testfile", "w")fh.write("這是一個測試文件,用于測試異常!!")
except Exception as e: log = traceback.format_exc()print(type(log), log)
traceback.print_exc()跟traceback.format_exc()有什么區別呢?
format_exc()返回字符串,print_exc()則直接給打印出來。
即traceback.print_exc()與print traceback.format_exc()效果是一樣的。
print_exc()還可以接受file參數直接寫入到一個文件。比如
traceback.print_exc(file=open('tb.txt','w+'))
寫入到tb.txt文件去。
?
總結
以上是生活随笔為你收集整理的Python traceback模块的使用(抛异常、报错、输出错误)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python requests 提示警告
- 下一篇: Nessus Plugins Downl