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

How to get the line number on which exception or error occurred in Python?

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

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

发生异常时打印"Specialization matching query does not exist.",但不打印行号。如何跟踪发生异常或错误的行号?

试试这个:

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

如果您出于任何原因不能使用日志记录,可以使用标准包 traceback,您可以执行以下操作:

traceback.print_exc(file=sys.stdout)

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

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