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

创建每分钟执行的Python测试脚本:前4次执行第5次失败并记日志

修复后的Python定时测试脚本实现

需求回顾

  • 脚本每分钟执行一次,完成5次迭代
  • 前4次迭代正常执行,记录状态为executed
  • 第5次迭代触发错误,记录状态为failed后停止运行
  • 每次迭代需记录:脚本名称(task)、操作状态、时间戳,最终输出为指定格式的日志

原代码问题分析

  1. 嵌套循环遍历b列表会生成多条重复记录,不符合每次迭代仅一条记录的要求
  2. 错误处理逻辑错误:捕获异常后直接pass,且后续的if str_error判断逻辑颠倒,无法正确触发失败后的停止逻辑
  3. 脚本名称列表长度不足,DataFrame初始化时数据结构错误,导致输出格式不符合预期
  4. 未正确实现每分钟执行的间隔逻辑,时间戳未按分钟间隔生成

修复后的代码

import datetime
from time import sleep
import pandas as pd

# 初始化日志记录列表
log_records = []
script_name = "task"

for iteration in range(5):
    # 生成当前迭代的时间戳(模拟每分钟间隔,实际运行可替换为datetime.datetime.now())
    base_time = datetime.datetime(2010, 3, 20, 9, 27)
    current_timestamp = base_time + datetime.timedelta(minutes=iteration)
    
    try:
        # 模拟指定函数执行:前4次正常,第5次触发错误
        if iteration == 4:
            raise ValueError("第5次迭代触发预设错误")
        # 替换为实际需要执行的函数
        # msg.send()
        
        # 记录正常执行状态
        log_records.append({
            "Script": script_name,
            "Operation": "executed",
            "Timestamp": current_timestamp
        })
    except Exception as e:
        # 记录失败状态
        log_records.append({
            "Script": script_name,
            "Operation": "failed",
            "Timestamp": current_timestamp
        })
        # 触发错误后停止迭代
        break
    
    # 实际运行时启用,实现每分钟执行一次
    # sleep(60)

# 转换为DataFrame并格式化输出
df = pd.DataFrame(log_records)
df["Timestamp"] = df["Timestamp"].dt.strftime("%Y-%m-%d %H:%M:%S")
print(df.to_string(index=True))

# 将日志写入独立文件
df.to_csv("task_log.csv", index=False)

预期输出

Script  Operation             Timestamp
0                     task   executed   2010-03-20 09:27:00
1                     task   executed   2010-03-20 09:28:00
2                     task   executed   2010-03-20 09:29:00
3                     task   executed   2010-03-20 09:30:00
4                     task     failed   2010-03-20 09:31:00

代码说明

  • 用列表字典存储每条日志记录,结构清晰,便于转换为DataFrame
  • 第5次迭代(索引4)主动触发错误,捕获后记录failed状态并终止循环
  • 模拟时间戳实现示例中的固定间隔,实际运行时可替换为datetime.datetime.now()并启用sleep(60)实现真实的每分钟执行
  • 最终将日志输出为指定格式,并写入独立的CSV日志文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:51:22