gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:50 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com