Python加密货币项目挖矿后余额重置无法多次挖矿问题求助
加密货币项目挖矿余额更新异常修复
故障根因
- Python 模块导入存在缓存机制,代码中反复执行
from anthonys_balance import lbalance读取的始终是首次导入的缓存值,不会读取后续写入到用户余额文件中的最新数值,导致第二次挖矿开始余额始终基于初始值计算 - 函数调用逻辑混乱:
mine函数内部递归调用自身、select函数末尾无意义调用mine,导致执行链路异常,无法正常循环触发挖矿操作 - 余额计算逻辑错误:已执行
lnbalance = lbalance + 1,后续写入文件和打印时额外多加了1,数值计算不符合预期 - 初始值处理冲突:新用户创建余额文件时的初始值,和全局导入的
anthonys_balance模块值存在冲突,首次启动时数值就可能错误
修复后代码
import os import time balance = 1 user = input("Username:") user_balance_file = f'{user}s_balance.py' user_log_file = f"{user}'s file" # 初始化用户余额文件 if not os.path.exists(user_balance_file): with open(user_balance_file, "w", encoding="utf-8") as f: f.write(f'lbalance = {balance}') # 封装读取最新余额的方法,不走模块导入避免缓存问题 def get_latest_balance(): with open(user_balance_file, "r", encoding="utf-8") as f: content = f.read().strip() return int(content.split("=")[1].strip()) # 封装更新余额的方法 def update_balance(new_balance): with open(user_balance_file, "w", encoding="utf-8") as f: f.write(f'lbalance = {new_balance}') # 同步更新日志文件 with open(user_log_file, "w", encoding="utf-8") as f: f.write(f'{user} has a balance of {new_balance} Coinons') def mine(): time.sleep(3) current_balance = get_latest_balance() new_balance = current_balance + 1 update_balance(new_balance) print(f'{user} has a balance of {new_balance} Coinons') print("mine success") input("Continue?") def select(): while True: os.system("clear") current_balance = get_latest_balance() print(f'{user} has a balance of {current_balance} Coinon') print("Mine = 1") print("Send = 2") options = input("Selection:") if options == "1": mine() # 可后续扩展send功能逻辑 if __name__ == "__main__": select()
修复说明
- 取消用模块导入的方式读取余额,封装独立的读写方法直接操作用户余额文件,彻底规避Python模块导入缓存问题
- 移除所有无意义的递归调用,改用
while True循环实现多次操作需求,用户挖矿完成后可反复触发操作 - 修正余额计算逻辑,挖矿一次仅加1,数值计算准确
- 简化冗余的文件操作逻辑,统一用
with open语法自动处理文件关闭,避免文件句柄泄漏
内容的提问来源于stack exchange,提问作者RTM Records
相关产品推荐
相关产品推荐

