如何获取Python中发生异常或错误的行号?

时间:2018-06-05 08:58:48

标签: python django django-orm

我有一个像这样的Django ORM查询:

try:
    specialization_object = Specialization.objects.get(name="My Test Specialization")
except Exception as ex:
    print(ex)

当出现异常时,它会打印"专业化匹配查询不存在。",但它不打印行号。如何跟踪发生异常或错误的行号?

3 个答案:

答案 0 :(得分:2)

试试这个:

import logging
logger = logging.getLogger(__name__)

try:
    specialization_object = Specialization.objects.get(name="My Test Specialization")
except Exception as ex:
    logger.info(ex, exc_info=True) # exc_info will add traceback

进一步阅读here

答案 1 :(得分:2)

如果您因任何原因无法使用日志记录,那么标准包traceback就可以执行以下操作:

traceback.print_exc(file=sys.stdout)

答案 2 :(得分:0)

我刚刚想出了一个简单的解决方案:

import traceback
try:
    specialization_object = Specialization.objects.get(name="My Test Specialization")
except Exception as ex:
    print(traceback.format_exc())