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

如何重置Python函数中的调用计数以实现循环计数逻辑?

如何重置Python函数中的调用计数以实现循环计数逻辑?

当然可以实现这种循环计数的需求!你不需要让函数“重启”,只需要在计数达到阈值时手动重置call_count变量就好,非常简单。

看你现在的代码,核心是要在call_count超过7时把它重置回1或者0,我帮你调整代码并加入这个逻辑:

首先,要确保在全局作用域里初始化call_count变量(比如设置初始值为0),然后在logger函数里更新计数后添加重置判断:

# 全局初始化计数变量,根据需求设置初始值(这里设为0)
call_count = 0

def logger():
    logging.basicConfig(level=logging.INFO, filename="anomaly.log", filemode="w", format="%(asctime)s - %(levelname)s - %(message)s")
    logger = logging.getLogger(__name__)
    logger.propagate = False

    handler = logging.FileHandler('anomaly.log')
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    handler.setFormatter(formatter)

    logger.addHandler(handler)
    try:
        # 优化:仅调用一次图片定位,避免重复执行相同操作
        location = pyautogui.locateOnScreen('1.png', confidence=0.9)
        if location:
            global call_count
            call_count += 1
            # 用f-string简化日志内容拼接
            logging.info(f"Found x1 {call_count} amount of times ")
            if call_count == 7:
                print('Hi')
            # 当计数超过7时重置为1(若需要从0开始则改为call_count = 0)
            if call_count > 7:
                call_count = 1
    except pyautogui.ImageNotFoundException:
        pass

# schedule 调度逻辑保持不变
schedule.every(1).seconds.do(logger)

while True:
    schedule.run_pending()
    time.sleep(1)

我还帮你优化了一个小细节:原来的代码里重复调用了两次pyautogui.locateOnScreen,其实只需要调用一次并把结果存在location变量中,后续直接判断location是否存在即可,这样能减少不必要的性能消耗。

如果你的需求是计数到7后立刻重置,也可以把重置逻辑整合到call_count == 7的判断分支里,这样更直观:

if call_count == 7:
    print('Hi')
    call_count = 0  # 重置为0,下次检测到图片时计数会从1开始

这样每次计数到7时,打印完Hi就会把计数清零,下一次触发计数时就从1重新开始,完美实现循环计数的效果。

最后提醒一下:全局变量call_count必须在函数外部提前初始化,否则运行时会抛出未定义的错误哦。

备注:内容来源于stack exchange,提问作者D3AD_SHOT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:48:07