Windows 10 Enterprise中Python定时程序存储临时整数的方案咨询
可行的几种轻量级存储方案
针对你的需求,这里有几个比纯文本文件更规范、又不用数据库的轻量级方案,适配Windows环境和Python程序:
1. JSON 文件
JSON是结构化的文本格式,比纯数字文本更规范,能明确键值关系,Python处理起来也很方便。
实现代码:
import json import os # 定义存储文件路径,比如放在程序同目录下 STORE_PATH = "counter.json" def get_counter(): if not os.path.exists(STORE_PATH): # 首次运行初始化 return 0 with open(STORE_PATH, "r") as f: data = json.load(f) return data.get("count", 0) def update_counter(new_count): with open(STORE_PATH, "w") as f: json.dump({"count": new_count}, f) # 主逻辑 current = get_counter() new_val = current + 1 update_counter(new_val) print(f"Updated counter to: {new_val}")
注意点:
- 可以给文件加个简单的锁(比如用
filelock库),避免极端情况下任务重叠运行导致的文件读写冲突 - JSON格式本身自带结构,后续扩展存储其他数据也很方便
2. Windows 注册表
既然是Windows系统,直接用注册表存储小整数是个很合适的选择——不用额外生成文件,系统原生支持,适合存储配置类小数据。
实现代码:
import winreg # 定义注册表路径(选HKCU,当前用户权限足够,不用管理员) REG_PATH = r"Software\MyPythonCounter" def get_counter(): try: key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_READ) count, _ = winreg.QueryValueEx(key, "CurrentCount") winreg.CloseKey(key) return count except FileNotFoundError: # 首次运行初始化 return 0 def update_counter(new_count): try: key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH) winreg.SetValueEx(key, "CurrentCount", 0, winreg.REG_DWORD, new_count) winreg.CloseKey(key) except Exception as e: print(f"Registry update failed: {e}") # 主逻辑 current = get_counter() new_val = current + 1 update_counter(new_val) print(f"Updated counter to: {new_val}")
注意点:
- 用
HKEY_CURRENT_USER路径不需要管理员权限,避免任务计划运行时的权限问题 - 注册表存储的
REG_DWORD类型正好对应整数,类型匹配更规范
3. INI 配置文件
用Python自带的configparser模块处理INI文件,这是专门用于配置存储的规范格式,可读性和结构化都比纯文本好。
实现代码:
import configparser import os STORE_PATH = "counter.ini" def get_counter(): config = configparser.ConfigParser() if not config.read(STORE_PATH): return 0 return config.getint("Counter", "value", fallback=0) def update_counter(new_count): config = configparser.ConfigParser() config["Counter"] = {"value": str(new_count)} with open(STORE_PATH, "w") as f: config.write(f) # 主逻辑 current = get_counter() new_val = current + 1 update_counter(new_val) print(f"Updated counter to: {new_val}")
注意点:
- INI格式天然适合分节存储配置,后续如果要加其他参数很方便
configparser会自动处理格式,不用手动拼接字符串,避免格式错误
内容的提问来源于stack exchange,提问作者Akshay J
相关产品推荐
相关产品推荐

