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

Python轮询库:为轮询迭代添加控制台日志的实现咨询

给轮询迭代添加日志的解决方案

没问题!给你的轮询每次迭代加上指定日志其实很容易实现,咱们不用修改现有poll方法的源码,只需要包装一下你传入的查询函数就能搞定。

方法一:定义带日志的包装函数(推荐,可读性更高)

首先导入datetime模块来获取当前时间,然后把原来的getSomething()调用包裹在一个带日志输出的函数里:

import datetime

def poll_with_log():
    # 生成格式化的当前时间字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 打印日志到控制台
    print(f"Waiting for the response {current_time}")
    # 执行原本的查询逻辑
    return getSomething()

然后把这个包装好的函数传给poll方法就行:

result = poll(poll_with_log, timeout=100, step=1, check_success=IsPollingSuccessfull)

方法二:用Lambda简化写法(适合简单场景)

如果不想单独定义函数,也可以直接在Lambda里先输出日志再执行查询:

import datetime

result = poll(
    lambda: (
        print(f"Waiting for the response {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"),
        getSomething()
    )[1],  # 取第二个元素作为返回值
    timeout=100,
    step=1,
    check_success=IsPollingSuccessfull
)

进阶:用标准logging模块输出(更规范)

如果你的项目已经在用Python的logging模块,替换print为日志方法会更符合项目规范:

import logging
import datetime

# 先配置日志基础设置(如果没配置过的话)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")

def poll_with_log():
    logging.info("Waiting for the response")
    return getSomething()

result = poll(poll_with_log, timeout=100, step=1, check_success=IsPollingSuccessfull)

这种方式会自动带上日志时间,不用手动格式化啦~

这样改动后,每次轮询执行时,控制台都会输出你想要的日志内容,完全不影响原来的轮询逻辑哦!

内容的提问来源于stack exchange,提问作者Mr.B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 09:42:27