#!/usr/bin/python
# -*- coding: UTF-8 -*-
import traceback
try:
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文件去。