Skip to main content
 首页 » 编程设计

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

2025年05月04日12freeliver54

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