python显示哪一行发生错误,以及什么错误

# coding: utf-8
# author: lovecjy
# created_time: 2020/9/27
"""
使用try...except...代码异常时,显示哪一行发生错误,以及什么错误
"""
import logging
try:
	print(a)
except Exception as e:
	# 错误的行和错误     error
	error_line = e.__traceback__.tb_lineno
	error_info = '第{error_line}行发生error为: {e}'.format(error_line=error_line, e=str(e))
	logging.error(error_info)

# 运行代码,结果:
# ERROR:root:第9行发生error为: name 'a' is not defined

以上。

posted @ 2020-09-28 14:35  慕夏一缕风  阅读(1551)  评论(0)    收藏  举报