[英]How to print an exception in Python 3?
現在,我在except Exception:
子句中捕獲異常,並執行print(exception)
。 結果不提供任何信息,因為它總是打印<class 'Exception'>
。 我知道這曾經在 python 2 中工作,但我如何在 python3 中做到這一點?
我猜您需要將Exception
分配給一個變量。 如Python 3 教程所示:
def fails():
x = 1 / 0
try:
fails()
except Exception as ex:
print(ex)
簡要說明一下, as
是在某些復合語句中使用的偽賦值關鍵字,用於將前面的語句賦值或別名給變量。
在這種情況下, as
將捕獲的異常分配給一個變量,允許存儲和稍后使用有關異常的信息,而不是需要立即處理。 (這在Python 3 語言參考: try
語句中有詳細討論。)
另一個使用as
復合語句是with
語句:
@contextmanager
def opening(filename):
f = open(filename)
try:
yield f
finally:
f.close()
with opening(filename) as f:
# ...read data from f...
這里, with
語句用於用上下文管理器定義的方法包裝塊的執行。 這就像一個擴展的try...except...finally
語句在一個整潔的生成器包中,並且as
語句將生成器生成的結果從上下文管理器分配給一個變量以供擴展使用。 (這在Python 3 語言參考中詳細討論: with
語句。)
最后, as
可導入時模塊,別名到一個不同的(通常較短)的名稱的模塊一起使用:
import foo.bar.baz as fbb
這在Python 3 語言參考: import
語句中有詳細討論。
這些是自 python 2 以來的變化:
try:
1 / 0
except Exception as e: # (as opposed to except Exception, e:)
# ^ that will just look for two classes, Exception and e
# for the repr
print(repr(e))
# for just the message, or str(e), since print calls str under the hood
print(e)
# the arguments that the exception has been called with.
# the first one is usually the message. (OSError is different, though)
print(e.args)
您可以查看標准庫模塊回溯以獲得更好的東西。
嘗試
try:
print undefined_var
except Exception as e:
print(e)
這將打印由e.__str__()
給出的表示:
“名稱 'undefined_var' 未定義”
您還可以使用:
print(repr(e))
這將包括異常類名:
"NameError("name 'undefined_var' 未定義",)"
這是我喜歡的打印所有錯誤堆棧的方式。
import logging
try:
1 / 0
except Exception as _e:
# any one of the follows:
# print(logging.traceback.format_exc())
logging.error(logging.traceback.format_exc())
輸出如下所示:
ERROR:root:Traceback (most recent call last):
File "/PATH-TO-YOUR/filename.py", line 4, in <module>
1 / 0
ZeroDivisionError: division by zero
LOGGING_FORMAT
:
LOGGING_FORMAT = '%(asctime)s\n File "%(pathname)s", line %(lineno)d\n %(levelname)s [%(message)s]'
雖然如果你想要一個與python2和python3兼容的代碼,你可以使用這個:
import logging
try:
1/0
except Exception as e:
if hasattr(e, 'message'):
logging.warning('python2')
logging.error(e.message)
else:
logging.warning('python3')
logging.error(e)
[在 Python3 中]
假設您要處理IndexError
並打印回溯,您可以執行以下操作:
from traceback import print_tb
empty_list = []
try:
x = empty_list[100]
except IndexError as index_error:
print_tb(index_error.__traceback__)
注意:您可以使用format_tb
函數而不是print_tb
將回溯作為用於日志記錄的字符串獲取。 希望這可以幫助。
我用過這個:
except (socket.timeout, KeyboardInterrupt) as e:
logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
break
如果它不適合您,請告訴我!!
不要使用print(e),因為它不會打印堆棧跟蹤,這是調試的噩夢。 traceback.print_exception 是你要找的:
import traceback
try:
assert False
except Exception as e:
traceback.print_exception(e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.