打包为exe后Python程序无法从py文件导入变量
问题描述
我为学校制作了一款Python游戏,需要打包成.exe文件提交。代码从独立.py文件导入所有变量,并用f.write写入变量保存。在Visual Studio中运行正常,但打包成.exe后出现问题:游戏保存变量后,文件可见写入内容,但运行时不读取这些变量,仍使用默认值。
处理变量导入的代码如下:
from save0 import * #Holds the 'savefile' variable if savefile == "save1.py": #Checks what file the user is using imports variables from that file. from save1 import * print("you are using save 1") os.system("pause") if savefile == "save2.py": print("you are using save 2") os.system("pause") from save2 import * if savefile == "save3.py": print("you are using save 3") os.system("pause") from save3 import * if savefile == "save4.py": print("you are using save 4") os.system("pause") from save4 import * if savefile == "save5.py": print("you are using save 5") os.system("pause") from save5 import *
我确认程序应导入预期文件,但无法理解为何不读取修改后的变量。程序无报错,已尝试调整auto-py-to-exe打包设置,仍未解决问题,恳请帮助。
问题原因
- Python模块缓存机制:
import语句会缓存模块内容,第一次导入后,后续调用from saveX import *会直接使用内存中的缓存版本,不会重新读取磁盘上修改后的文件内容。 - 打包后的路径问题:PyInstaller(auto-py-to-exe基于它)会将所有.py文件打包到.exe内部的临时目录,你手动修改的可能是外部的同名文件,而程序实际读取的是打包时的缓存版本。
解决方案
1. 动态读取存档文件内容
替换静态的import语句,改为直接读取并执行存档文件的内容,确保每次都获取最新修改:
import os from save0 import savefile def load_save(save_filename): if os.path.exists(save_filename): with open(save_filename, 'r') as f: # 执行文件内容并将变量注入当前命名空间 exec(f.read(), globals()) if savefile == "save1.py": load_save("save1.py") print("you are using save 1") os.system("pause") elif savefile == "save2.py": load_save("save2.py") print("you are using save 2") os.system("pause") # 其他存档文件同理
2. 明确存档文件的绝对路径
打包后程序的工作目录可能和预期不符,需确保读写的是同一个文件:
import os # 获取程序所在的绝对目录 app_root = os.path.dirname(os.path.abspath(__file__)) # 拼接存档文件的绝对路径 target_save = os.path.join(app_root, savefile) # 读取时用target_save路径 if os.path.exists(target_save): with open(target_save, 'r') as f: exec(f.read(), globals()) # 保存时也用这个路径 with open(target_save, 'w') as f: f.write(f"score = {score}\nlevel = {level}")
3. 改用标准存档格式(推荐)
放弃用.py文件存变量,改用JSON、Pickle或INI这类专门的存档格式,彻底规避模块缓存和打包路径问题:
示例:JSON格式存档
保存变量:
import json # 要保存的游戏数据 save_data = { "score": 150, "level": 3, "unlocked_items": ["sword", "shield"] } # 写入JSON文件 with open("save1.json", 'w') as f: json.dump(save_data, f, indent=4)
读取变量:
import json # 设置默认值,避免文件不存在时出错 default_data = {"score": 0, "level": 1, "unlocked_items": []} try: with open("save1.json", 'r') as f: save_data = json.load(f) except FileNotFoundError: save_data = default_data # 提取变量使用 score = save_data["score"] level = save_data["level"]
内容的提问来源于stack exchange,提问作者Oskar Altena
相关产品推荐
相关产品推荐

