如何在 python 中打印 Deprecation Warning 消息的调用方法名称和行号?

How to print the calling method name and line number for Deprecation Warning message in python?

我的弃用警告消息在一个函数中。我想打印出调用函数的模块名称和行号,以便我可以轻松找到它们。以open()为例:

/path/to/file/group.py:180: DeprecationWarning: 'U' mode is deprecated 
with open(tmpName, 'rU') as csvfile

然而,我自己的警告打印如下:

/path/to/file/models.py:735: DeprecationWarning: Deprecated. Use course_id instead! 
warnings.warn("Deprecated. Use course_id instead!", DeprecationWarning)

models.py 的第 735 行是 warnings.warn() 调用所在的位置。有没有办法让警告输出父调用者的姓名和行号?谢谢。

您可以使用 stacklevel 参数来控制要将警告应用到哪个来电者。

例如下面的代码:

import warnings

def hello(s):
    if isinstance(s, int):
        deprecation('Use of integers is deprecated.')
    else:
        print(s)

def deprecation(msg):
    warnings.warn(msg, DeprecationWarning, stacklevel=3)

hello(1)

会给出如下警告:

warning_test.py:12: DeprecationWarning: Use of integers is deprecated.
  hello(1)

参见:Python documentation on warnings.warn