首页 > 解决方案 > 在 python 中打印警告时如何引用正确的文件?

问题描述

我刚开始warnings在 python 中使用该模块。当我发出警告时,我试图了解如何在给定文件中引用正确的行。

我正在编写一个模块,其中某些功能可以发出警告,但我希望所有警告都指向它们在导入模块的脚本中发出的行,而不是指向它们在模块本身中发出的行。我想我明白了stacklevel参数的warnings.warn工作原理,但是我看不到如何将它与我的模块的功能一起使用,这些功能也在内部使用,因为它们的堆栈级别可能会有所不同。

我会尝试用一个例子让自己清楚。假设我编写了以下模块,我称之为testmodule.py.

import warnings

def f():
    warnings.warn('This is a test warning.', stacklevel=2)

def g():
    f()

然后我编写以下脚本。

import testmodule as test

test.f()
test.g()

如果我运行这个脚本,输出是

"script_filename":3: UserWarning: This is a test warning.
  test.f()
"module_filename":7: UserWarning: This is a test warning.
  f()

where"script_filename""module_filename"是我在计算机上保存脚本和模块的文件的实际名称。

在上面的示例中,两个警告都正确标识了f调用的行。test.g但是,在调用内部的点时发出警告testmodule,因此对模块的用户没有用处。有没有办法让这两个警告都指向它们在脚本中发出的行,而不是在模块本身中?

标签: pythonwarnings

解决方案


通过这些小的更改,我得到了您所要求的确切行为。添加参数g()可能不是您想要的,但我认为这是一个答案,并且可以帮助您理解。

import warnings

def f(slevel=2):
    warnings.warn('This is a test warning.', stacklevel=slevel)

def g(i):
    f(i)
import testmodule  as test

test.f()
test.g(3)

输出

script_filename:3: UserWarning: This is a test warning.
  test.f()
script_filename:4: UserWarning: This is a test warning.
  test.g(3)

推荐阅读