如何用Python跟踪《漫威SNAP》实时更新的GameState.json文件?
漫威SNAP游戏状态追踪程序入门指南
你的代码能否处理实时更新的文件?
直接用json.load()一次性读取文件的方式不能处理实时更新场景,原因如下:
- 这段代码仅读取一次文件内容,执行完毕后不会监听文件后续变化
- 若游戏正在写入
GameState.json时触发读取,很大概率会读到不完整的JSON数据,直接引发解析错误
基础实现思路(适合Python新手)
1. 监听文件变化
使用Python第三方库watchdog(需先执行pip install watchdog安装)监听文件修改事件,每次文件更新时重新读取解析。
2. 安全读取JSON文件
由于游戏可能正在写入文件,读取时需处理异常情况:
- 捕获JSON解析错误,遇到不完整数据时跳过本次读取,等待下一次文件更新
- 用
with语句读取文件,确保文件句柄自动关闭,避免资源泄漏
3. 可运行示例代码
import json from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class GameStateHandler(FileSystemEventHandler): def on_modified(self, event): # 仅处理目标JSON文件,忽略目录变化 if event.src_path.endswith("GameState.json") and not event.is_directory: try: with open(event.src_path, 'r', encoding='utf-8-sig') as f: game_state = json.load(f) # 替换为你需要的业务逻辑,比如打印关键数据 print("=== 回合状态更新 ===") for key, value in game_state.items(): print(f"{key}: {value}") except json.JSONDecodeError: print("读取到不完整JSON,跳过本次更新") except Exception as e: print(f"文件读取出错:{str(e)}") if __name__ == "__main__": # 替换为你的GameState.json实际路径 json_file_path = "C:/Path/To/Your/GameState.json" event_handler = GameStateHandler() observer = Observer() # 监听文件所在目录,而非单个文件 observer.schedule(event_handler, path="/".join(json_file_path.split("/")[:-1]), recursive=False) observer.start() try: # 保持程序运行,直到按下Ctrl+C终止 while True: pass except KeyboardInterrupt: observer.stop() observer.join()
新手实用提示
- 先定位
GameState.json的准确路径:漫威SNAP的日志文件通常在游戏安装目录或用户文档目录下,可通过游戏设置的日志选项确认位置 - 测试时可手动修改
GameState.json(比如添加空格),验证程序是否触发更新 - 避免在读取文件时手动修改它,防止与游戏的写入操作冲突
- 若不需要严格实时监听,也可以用定时轮询方式(每隔2秒读取一次),无需额外安装库,示例代码如下:
import json import time json_file_path = "你的文件路径" last_modified = 0 while True: current_modified = os.path.getmtime(json_file_path) if current_modified != last_modified: last_modified = current_modified try: with open(json_file_path, 'r', encoding='utf-8-sig') as f: game_state = json.load(f) print(game_state) except json.JSONDecodeError: pass time.sleep(2)
内容的提问来源于stack exchange,提问作者tlars25
相关产品推荐
相关产品推荐

