如何阻止PyInstaller生成的临时文件被自动删除?
Hey there, dealing with a 10GB reload every time your Flask app starts must be frustrating—let's fix that. Here are the most practical solutions depending on your needs:
1. Switch to --onedir Mode (Best for Large Apps)
The root issue here is that you're using PyInstaller's --onefile mode, which automatically extracts all your app's files to a temporary _MEIPASS folder and deletes it on exit. Instead, use the directory mode which skips the temporary extraction entirely:
- Run this command to build your app:
pyinstaller --onedir your_flask_app.py - Once built, all your app's files will live in the
dist/your_flask_appdirectory. You just need to run the executable inside that folder directly. - Pros: No more repeated extraction—starts instantly, no temp file cleanup to worry about.
- Cons: You'll have to distribute the entire directory instead of a single EXE file.
2. Use a Fixed Custom Temp Directory (If You Need --onefile Mode)
If you must keep the single EXE distribution, you can force PyInstaller to use a permanent custom directory instead of the system's temporary folder. This way, the files stay intact between sessions:
Step 1: Specify a Custom Runtime Temp Directory
Build your app with the --runtime-tmpdir flag to point to a fixed location:
pyinstaller --onefile --runtime-tmpdir "C:/FlaskAppTemp" your_flask_app.py
(Replace the path with one that makes sense for your OS—e.g., ~/FlaskAppTemp on Linux/macOS)
Step 2: Prevent PyInstaller From Deleting the Directory
By default, PyInstaller still deletes the temp folder on exit. To stop this, tweak your app's code to intercept the cleanup process:
- Add this snippet early in your Flask app (before any other imports that rely on
_MEIPASS):import sys import os import atexit # Check if we're running from a PyInstaller onefile build if hasattr(sys, '_MEIPASS'): # Remove PyInstaller's default temp folder cleanup handler for handler in atexit._exithandlers: if handler[0].__name__ == '_cleanup': atexit.unregister(handler[0]) break - Note: Add occasional manual cleanup logic for old temp files later—otherwise the directory will grow as you update your app.
3. Bonus: Optimize Bundle Size (Optional)
While this doesn't stop temp file deletion, trimming your bundle size will speed up initial loads if you stick with --onefile:
- Exclude unnecessary modules with
--exclude-module:pyinstaller --onefile --exclude-module tkinter --exclude-module pandas your_flask_app.py - Use UPX compression (install UPX first) with the
--upx-dirflag:pyinstaller --onefile --upx-dir /path/to/upx your_flask_app.py
内容的提问来源于stack exchange,提问作者Ugurcan

