如何修复语句弃用警告

2024-09-19 12:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些使用结构上下文管理器的Python代码,比如:

with settings(warn_only=True), hide('running', 'stdout', 'stderr', 'warnings'):
    do_stuff()

每次我运行这个程序,Python都会给我一个deprecation警告:

^{pr2}$

为什么我会收到这个警告?我该如何修复它?在

我有点困惑,因为this similar question意味着我正在使用嵌套管理器,而解决方法是将它们重写为我已经在使用的单行版本。在

我试着写:

with settings(warn_only=True) as a, hide('running', 'stdout', 'stderr', 'warnings') as b:
    do_stuff()

以及:

with settings(warn_only=True):
    with hide('running', 'stdout', 'stderr', 'warnings'):
        do_stuff()

但两者都给了我同样的警告。在


Tags: true警告only管理器settingsaswithstderr
2条回答

似乎Fabric本身正在使用不推荐使用的contextlib.nested。在

https://github.com/fabric/fabric/issues/1364

关于罚单的唯一建议似乎是忽略它,因为他们希望保持与旧版本Python的向后兼容性。在

一网打尽的解决方案是在程序顶部添加以下内容:

import warnings

warnings.simplefilter("ignore", DeprecationWarning)

基本上,这会阻止显示任何不推荐警告。在

以下是一些了解警告的链接。希望这有帮助!在

https://docs.python.org/2.7/library/warnings.html

https://www.idiotinside.com/2016/12/17/python-warnings-framework/

相关问题 更多 >