我似乎无法抑制这个弃用警告。 通常在单元测试中,我会强制对错误发出警告,然后如果在当前堆栈中无法修复则忽略它们。 我目前使用的是Python 3.12.1
这是重现的代码:
import warnings
import datetime
# warnings.simplefilter('error')
warnings.filterwarnings(action="ignore", message="datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).", category=DeprecationWarning)
datetime.datetime.utcnow()
运行这个,我得到:
$ python3.12 /tmp/foo.py
/tmp/foo.py:7: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
datetime.datetime.utcnow()
我还尝试在 python3.12.1 源代码树中编辑 warnings.py ,然后意识到由于 utcnow() 是下面的 C 模块,它只是直接调用 python 中的 _warnings.c 。 所以它在Python中是不可追踪的。 我已附加 gdb 并在
warn_explicit
上进行了中断,但尚未弄清楚如何检查 PyObject 内的字符串。
我在这里做错了什么明显或不明显的事情吗?
正如问题中@jhasonharper 的评论所提到的,
message
实际上是一个正则表达式:
这会检查参数的类型,编译消息和模块正则表达式,并将它们作为元组插入警告过滤器列表中。
这足以捕获警告:
warnings.filterwarnings(action="ignore", message=r"datetime.datetime.utcnow")
这也有效:
warnings.filterwarnings(action="ignore",
message=r"datetime.datetime.utcnow\(\) is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now\(datetime.UTC\).")