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

如何在python中打印弃用警告消息的调用方法名称和行号?,python,deprecated,Python,Deprecated,我的弃用警告消息在函数中。我想打印出调用函数的模块名和行号,以便轻松找到它们。以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 i

我的弃用警告消息在函数中。我想打印出调用函数的模块名和行号,以便轻松找到它们。以
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)

请参阅:

Aha!我太专注于DeprecationWarning的文档,而不是warn()。谢谢