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

标签 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 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

关于python - 如何在 python 中打印弃用警告消息的调用方法名称和行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31465483/

相关文章:

java - 构造函数 Time 已弃用

Android WebView PictureListener 已弃用 - 仍然别无选择?

python - pytest 添加选项以跳过 fixture 设置

python - 对 numpy 数组进行切片以选择列表中包含值的行。真值误差

python - python 2. 7's download package "Windows x86 MSI程序数据库”的目的是什么?

android - NetworkInfo 已被 API 29 弃用

javascript - "undocumented and incredibly non-performant way to monitor setting and getting of values"是什么?

Python - 替换 exec 来动态创建变量

python - 为什么 six.py 使用自定义类来查找 MAXSIZE?

java - Form 类中的方法 form(Class<T>) 在 Play 中已弃用!框架