python - 在 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
,因此对模块的用户没有用处。有没有办法让这两个警告都指向它们在脚本中发出的行,而不是在模块本身中?
解决方案
通过这些小的更改,我得到了您所要求的确切行为。添加参数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)
推荐阅读
- featuretools - featuretools:为什么 dfs() 做冗余计算?
- hugo - Page.Title 与 Hugo 网站上的 Site.Title 相同
- php - 无法仅从模型页面获取 URL 段
- c - 为什么不按位计算器程序打印?
- sql - 当前和未来 3 周的总计相同,而不是运行总计
- jquery - 向 Laravel DataTable 控制器函数发送参数
- django - Django - 带有休息框架的数据表ajax错误
- reactjs - 如何保证通过Functional Components传递的props总是被更新,而不是为每一层的props写一个useEflect?
- apache-nifi - NiFi - 合并分页 API 返回的数据
- flutter - 如何在颤动中制作带有视频文件的gif文件