PyInstaller打包单文件exe后程序重复启动问题求助
问题:PyInstaller打包的EXE重复启动,疑似与subprocess相关
我使用命令pyinstaller --onefile -w script.py将Python脚本打包为EXE文件,但运行该EXE时程序会多次重复启动。半年前曾成功完成相同操作,如今更新代码后重新打包,无论如何操作都会出现重复启动的情况,怀疑这与代码中的subprocess部分有关,相关代码如下:
zip_files = [f for f in os.listdir(data_analysis_folder) if f.endswith(".zip") # file should end with .zip as extension and os.path.getsize(os.path.join(data_analysis_folder, f)) > 2048] # should be bigger than 2kb to convert zip_files_zipped = len(zip_files) errors = [] for zip_file in zip_files: file_path = os.path.join(data_analysis_folder, zip_file) result = subprocess.Popen([program, "x", "-y", "-p" + password_customer, file_path, "-o" + data_analysis_folder], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) result.wait() # The -y argument in the subprocess run confirms the replacement of the files automatically if result.returncode != 0: print(f"Error extracting {zip_file}: {result.stderr}") errors.append(f'Error extracting {zip_file}: {result.stderr}') errors_df = pd.DataFrame(errors) errors_df.to_csv(data_analysis_folder + str("/errors_zipping.csv"), index=False, decimal=",")
可能的原因及解决办法
program变量指向错误:这是最常见的触发原因。如果你的program没有正确指向解压缩工具(比如7-Zip的7z.exe),而是不小心指向了当前打包后的EXE文件,每次调用subprocess.Popen就会重新启动自身,形成无限循环。- 解决:把
program改成解压缩工具的绝对路径,比如program = "C:\\Program Files\\7-Zip\\7z.exe",确保路径准确无误。
- 解决:把
OneFile模式的临时目录问题:
--onefile打包时,程序运行会先把自身解压到系统临时目录,如果你用相对路径指定program,可能找不到真正的解压缩工具,反而误启动了临时目录里的自身副本。- 解决:要么用绝对路径,要么在打包时通过
--add-data把解压缩工具一起打包进去,然后在代码里获取打包后的工具路径。
- 解决:要么用绝对路径,要么在打包时通过
调试时去掉
-w参数:-w会隐藏控制台窗口,导致你看不到subprocess调用时的错误信息(比如找不到程序、参数错误)。先打包成带控制台的版本:pyinstaller --onefile script.py,运行后看控制台输出,能直接定位问题。UPX压缩导致的异常:部分情况下,UPX压缩会破坏subprocess调用的逻辑,试试添加
--noupx参数打包:pyinstaller --onefile -w --noupx script.py。
内容的提问来源于stack exchange,提问作者Luuk_148
相关产品推荐
相关产品推荐

