You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何捕获Python‘coroutine was never awaited’警告并触发异常

解决未await协程警告被忽略的问题

方法1:将特定警告转为致命异常

直接用Python的warnings模块精准匹配未await协程的警告信息,把它升级为错误。这样只要忘加await,程序会直接抛出异常终止,不会只输出容易被忽略的警告。

示例代码(放在测试套件入口,比如conftest.py或测试启动文件):

import warnings

# 匹配"coroutine was never awaited"相关警告,转为错误
warnings.filterwarnings(
    "error",
    message=r".*coroutine.*was never awaited.*",
    category=RuntimeWarning
)

方法2:结合asyncio调试模式强化检查

开启asyncio调试模式后,会额外输出协程的创建栈信息,配合警告转错误的设置,能帮你更快定位问题代码:

import asyncio
import warnings

# 启用asyncio调试模式
asyncio.get_event_loop().set_debug(True)

# 将目标警告转为错误
warnings.filterwarnings(
    "error",
    message=r".*coroutine.*was never awaited.*",
    category=RuntimeWarning
)

方法3:自定义醒目警告提示

如果不想直接终止程序,只想让警告在日志里更显眼,可以重写警告输出函数,用彩色加粗样式突出:

import warnings
import sys

def bold_red_warning(message, category, filename, lineno, file=None, line=None):
    # 用ANSI转义码输出红色加粗的警告内容
    target_file = file or sys.stderr
    warning_msg = f"\033[1;31m{category.__name__}: {message}\033[0m\n"
    target_file.write(warning_msg)

# 替换默认的警告展示逻辑
warnings.showwarning = bold_red_warning

pytest用户专属配置

如果你用pytest做测试框架,还可以直接在pytest.ini里配置,不用改代码:

[pytest]
filterwarnings =
    error::RuntimeWarning:.*coroutine.*was never awaited.*

内容的提问来源于stack exchange,提问作者Jeremy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:05:16