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

如何在pytest中禁用live log setup/teardown,仅查看live log call?

仅查看pytest的"live log call"日志方案

pytest本身没有直接的内置选项仅显示live log call阶段的日志,但可以通过以下两种方式实现:

方法一:自定义pytest插件(推荐)

在项目根目录创建conftest.py文件,添加以下代码,通过过滤日志记录的阶段属性实现仅保留call阶段日志:

import logging
from _pytest.logging import LiveLogHandler

def pytest_configure(config):
    # 定位live log处理器
    live_log_handler = next(
        (h for h in logging.root.handlers if isinstance(h, LiveLogHandler)),
        None
    )
    if live_log_handler:
        # 替换日志过滤器,仅保留call阶段的日志
        def filter_call_only(record):
            return record.__dict__.get("_stage") == "call"
        live_log_handler.filter = filter_call_only

原理:pytest的live log会为每条日志记录添加_stage额外属性,取值为setup/call/teardown,通过过滤器只放行call阶段的日志即可。

方法二:命令行过滤(临时快速方案)

如果不想修改代码,可以结合命令行工具过滤输出:

Linux/macOS(使用awk)

pytest --live-log | awk '/live log call/{flag=1;next}/live log teardown/{flag=0}flag'

Windows(PowerShell)

pytest --live-log | Select-String -Pattern "live log call" -Context 0, 10000 | ForEach-Object { $_.Line; $_.Context.PostContext } | Where-Object { $_ -notmatch "live log setup|live log teardown" }

这样就能只提取出live log call阶段的所需日志,屏蔽setup和teardown的冗余内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:15:33