[英]How to suppress these fake warnings coming from aiohttp?
I've got some code that makes requests to remote sites using asyncio
and aiohttp
.我有一些代码可以使用
asyncio
和aiohttp
向远程站点发出请求。
import aiohttp, asyncio
async def f():
session = aiohttp.ClientSession()
async with session.get('https://httpbin.org/get') as response:
pass
asyncio.run(f())
When I run it, it produces当我运行它时,它会产生
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f56796b3d68>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7f56793836a8>, 0.0)]']
connector: <aiohttp.connector.TCPConnector object at 0x7f56796b3f98>
Now, the way I make requests is not recommended (for various reasons), which is why I'm getting those messages.现在,不推荐我提出请求的方式(出于各种原因),这就是我收到这些消息的原因。 However, they sure won't stop me, and so I just wish to never see them again.
然而,他们肯定不会阻止我,所以我只想再也见不到他们。
I reasonably assumed that they are normal warnings and tried disabling them via the -Wignore
command line option, as well as by putting the following code at the start of the script我合理地假设它们是正常警告并尝试通过
-Wignore
命令行选项以及将以下代码放在脚本的开头来禁用它们
import warnings
warnings.filterwarnings('ignore')
but the messages kept appearing.但消息不断出现。 How come?
怎么来的? How can I suppress them?
我怎样才能压制它们?
Turns out, aiohttp
not only emits normal warnings with that text, but also calls the exception handler of the loop with the same message during the unexceptional __del__
invocation.事实证明,
aiohttp
不仅会使用该文本发出正常警告,还会在无异常的__del__
调用期间使用相同的消息调用循环的异常处理程序。
Source for ClientSession
: ClientSession
来源:
def __del__(self, _warnings: Any=warnings) -> None:
if self._protocol is not None:
...
_warnings.warn('Unclosed connection {!r}'.format(self),
ResourceWarning,
**kwargs)
...
context = {'client_connection': self,
'message': 'Unclosed connection'}
...
self._loop.call_exception_handler(context) # <---
Thus, if you only want to suppress the warnings that come from the aiohttp
library and through the loop's exception handler, you have to either因此,如果您只想抑制来自
aiohttp
库和循环异常处理程序的警告,您必须要么
For example, with a no-op function:例如,使用 no-op 函数:
async def f():
asyncio.get_running_loop().set_exception_handler(lambda loop, context: None)
...
# No output
or或者
asyncio
moduleasyncio
模块的日志记录级别Because the loop's default exception handler logs the exception messages with the logging.ERROR
level, you will have to set the level to logging.CRITICAL
由于循环的默认异常处理程序使用
logging.ERROR
级别记录异常消息,因此您必须将级别设置为logging.CRITICAL
import logging
async def f():
logging.getLogger('asyncio').setLevel(logging.CRITICAL)
...
# No output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.