简体   繁体   English

如何修复语句弃用警告

[英]How to fix with statement deprecation warning

I have some Python code, using Fabric context managers, like: 我有一些Python代码,使用Fabric上下文管理器,如:

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

and every time I run this, Python gives me the DeprecationWarning: 每次我运行它,Python都会给我DeprecationWarning:

With-statements now directly support multiple context managers
  with settings(warn_only=True), hide('running', 'stdout', 'stderr', 'warnings'):

Why am I getting this warning and how do I fix it? 为什么我收到此警告以及如何解决?

I'm a bit confused, because this similar question implies I'm using nested managers, and that the fix is to rewrite them into the single line version that I'm already using. 我有点困惑,因为这个类似的问题意味着我正在使用嵌套管理器,并且修复是将它们重写为我已经使用的单行版本。

I've tried re-writing it like: 我试过重写它像:

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

and: 和:

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

but both give me the same warning. 但两人都给了我同样的警告。

It seems to be that Fabric itself is using the deprecated contextlib.nested . 似乎Fabric本身正在使用已弃用的contextlib.nested

See https://github.com/fabric/fabric/issues/1364 请参阅https://github.com/fabric/fabric/issues/1364

The only suggestion on the ticket seems to be to ignore it as they want to maintain backward compatibility with older versions of Python. 票证上唯一的建议似乎是忽略它,因为他们希望保持与旧版Python的向后兼容性。

The catch-all solution would be adding this at the top of your program: 全能的解决方案是在程序的顶部添加:

import warnings

warnings.simplefilter("ignore", DeprecationWarning)

Basically, this stops any DeprecationWarning from displaying. 基本上,这会阻止任何DeprecationWarning显示。

Here's a couple links for understanding warnings. 这里有一些用于理解警告的链接。 Hope this helped! 希望这有帮助!

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM