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

如何在Notebook中保存历次手动输入参数以实现追踪记录?

追踪Notebook历史输入参数的几种方法
  • 本地JSON文件存储
    直接把每次的输入参数写入本地JSON文件,操作简单,还能加时间戳方便追溯。示例代码:

    import json
    from datetime import datetime
    
    # 当前设置的输入参数
    input1 = 3
    input2 = "a"
    input3 = 10.5
    
    # 构造带时间戳的记录
    param_record = {
        "timestamp": datetime.now().isoformat(),
        "input1": input1,
        "input2": input2,
        "input3": input3
    }
    
    # 读取已有历史(文件不存在就新建空列表)
    try:
        with open("param_history.json", "r", encoding="utf-8") as f:
            history = json.load(f)
    except FileNotFoundError:
        history = []
    
    # 追加新记录并保存
    history.append(param_record)
    with open("param_history.json", "w", encoding="utf-8") as f:
        json.dump(history, f, indent=2)
    

    每次运行Notebook,当前参数都会被追加到JSON文件里,后续打开文件就能看到所有历史输入。

  • SQLite数据库存储
    如果需要按条件查询历史(比如找某段时间的参数、特定值的记录),用SQLite更合适——Python自带支持,不用额外装数据库。示例代码:

    import sqlite3
    from datetime import datetime
    
    input1 = 3
    input2 = "a"
    input3 = 10.5
    
    # 连接数据库(不存在则自动创建)
    conn = sqlite3.connect("param_history.db")
    cursor = conn.cursor()
    
    # 第一次运行时创建表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS param_records (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT NOT NULL,
            input1 INTEGER,
            input2 TEXT,
            input3 REAL
        )
    ''')
    
    # 插入当前参数记录
    cursor.execute('''
        INSERT INTO param_records (timestamp, input1, input2, input3)
        VALUES (?, ?, ?, ?)
    ''', (datetime.now().isoformat(), input1, input2, input3))
    
    conn.commit()
    conn.close()
    

    要查看历史的话,执行查询即可:

    conn = sqlite3.connect("param_history.db")
    cursor = conn.cursor()
    # 按时间倒序查询最近的记录
    cursor.execute("SELECT * FROM param_records ORDER BY timestamp DESC")
    for row in cursor.fetchall():
        print(row)
    conn.close()
    
  • Notebook内临时追踪+持久化
    如果想在Notebook会话里随时看历史,同时避免关闭后丢失,可以在开头定义一个全局历史列表,每次运行时追加,再同步到文件:

    # 放在Notebook最顶部,仅初始化一次
    try:
        param_history
    except NameError:
        param_history = []
    
    # 当前输入参数
    input1 = 3
    input2 = "a"
    input3 = 10.5
    
    # 添加到历史列表
    param_history.append({
        "timestamp": datetime.now().isoformat(),
        "input1": input1,
        "input2": input2,
        "input3": input3
    })
    
    # 同步到文件,防止Notebook关闭丢失
    import json
    with open("param_history.json", "w", encoding="utf-8") as f:
        json.dump(param_history, f, indent=2)
    

    这样在Notebook里直接打印param_history就能看到当前会话的所有输入,文件里也会保留完整历史。

内容的提问来源于stack exchange,提问作者Raphaël Ambit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:55:13