【问题标题】:Is there a way to see which line of code produces warning message in python?有没有办法查看哪一行代码在 python 中产生警告消息?
【发布时间】:2020-11-21 01:48:30
【问题描述】:

Python 经常抛出警告消息,尤其是在使用 pandas 时。但没有显示线参考。为什么会这样?有没有办法获取这些信息?

【问题讨论】:

标签: python warnings


【解决方案1】:

对于不是 pandas 特定的更通用的解决方案,您可以覆盖 formatwarning 方法:

警告信息的打印是通过调用 showwarning() 来完成的, 可能会被覆盖;此函数的默认实现 通过调用 formatwarning() 格式化消息,这也是 可供自定义实现使用。

所以它看起来像下面这样:

import warnings

def my_formatwarning(message, category, filename, lineno, line=None):
  print(message, category)
  # lineno is the line number you are looking for
  print('file:', filename, 'line number:', lineno) 
  ...

warnings.formatwarning = my_formatwarning

对于问题的部分原因,我不确定答案是什么,我想是为了让日志保持清洁?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2023-01-31
    相关资源
    最近更新 更多