Quick answer: “Failed to execute script ‘main’ due to unhandled exception” means your own Python code raised an exception that nothing caught; PyInstaller’s bootloader is only reporting it. Rebuild with --onedir --console, run the exe from a terminal and read the traceback. In a Pygame game it is usually an asset that was never bundled with --add-data, a path that depends on the working directory, a hidden import, or code that touches sys.stdout in a windowed build.
The game runs with python main.py. You build it with PyInstaller, double-click the exe, and get a dialog saying it failed to execute the script. Nothing is wrong with PyInstaller at that point: the frozen interpreter started, ran your code, and your code raised. The whole job is getting the traceback back, then fixing the one thing that differs between your source folder and the bundle. This guide gives the exact message for each PyInstaller version, three ways to see the traceback, and the causes that only show up once a Pygame game is frozen, each with its fix.
- The exact error
- Get the traceback first
- What causes it in a Pygame game
- Fix 1: bundle the assets and resolve paths from the bundle
- Fix 2: stop using a console that is not there
- Fix 3: hidden imports and package data
- Fix 4: write saves and logs to a per-user folder
- Fix 5: call freeze_support()
- Leave a crash log for players
- Similar failures that are not this error
- How to confirm the fix
- Getting the traceback from players automatically
- Related guides
- Frequently asked questions
The exact error
A windowed build (--windowed / --noconsole) on Windows made with PyInstaller 4.4 or later shows a dialog titled Unhandled exception in script:
Failed to execute script 'main' due to unhandled exception: No file 'assets/player.png' found in working directory 'C:\Users\Sam\Downloads'.
Traceback (most recent call last):
File "main.py", line 12, in <module>
File "main.py", line 7, in load
FileNotFoundError: No file 'assets/player.png' found in working directory 'C:\Users\Sam\Downloads'.
A console build prints the normal Python traceback and then one summary line. The prefix is the process ID, and its format changed in PyInstaller 6:
[9412] Failed to execute script 'main' due to unhandled exception!
[PYI-9412:ERROR] Failed to execute script 'main' due to unhandled exception!
PyInstaller 4.3 and older say less. A windowed build shows a message box titled “Fatal error detected” with no traceback at all:
Failed to execute script main
All of these mean the same thing. The name in the message is your entry script, not the file that failed. If the traceback box reads “Traceback is disabled via bootloader option.”, the build was made with --disable-windowed-traceback; remove that flag while you debug. On macOS a windowed .app shows no dialog, and the message goes to stderr and the system log.
Get the traceback first
Do not guess from the dialog. Pick whichever of these is fastest for you:
- Read the dialog. On PyInstaller 4.4 and later the Windows dialog already contains the traceback in a scrollable box. The last line is the exception; the lines above it are the path through your code.
- Build with a console and run from a terminal. This is the reliable one, and the only option on old PyInstaller versions:
Run it from an already open Command Prompt or PowerShell window. If you double-click a console build, the window closes before you can read it. On macOS runpyinstaller --onedir --console main.py cd dist\main main.exe./dist/mainfrom Terminal instead of opening the.app. On Linux--windowedis ignored, so run./dist/main/main. - Write it to a file. For a build already in a tester’s hands, wrap the entry point as shown in the crash log section and ask for the file.
If the traceback ends in ModuleNotFoundError or ImportError, also open build/main/warn-main.txt. PyInstaller writes every module it could not find during analysis there. Most entries are harmless, but the module in your traceback will be on the list.
What causes it in a Pygame game
Ordered by how often each one is the answer:
- Assets were never bundled. PyInstaller follows
importstatements. It does not know aboutpygame.image.load("assets/player.png"), so images, sounds, fonts, level files and shaders stay behind unless you list them. - Paths depend on the working directory. Even with the assets bundled, a relative path is resolved against wherever the player launched from, not against the bundle.
- Code that uses
sys.stdout,sys.stderrorinput()in a windowed build, where those objects areNone. - Hidden imports. Modules loaded by name at runtime (
importlib.import_module,__import__, plugin folders) and some packages’ data files. - Writing saves or logs into the bundle. The install folder may be read-only, and a onefile build’s folder is temporary.
multiprocessingwithoutfreeze_support().
Things that look similar but are different errors: a build made on a newer OS than the player’s, antivirus removing files, and loader failures. Those are covered under similar failures.
Fix 1: bundle the assets and resolve paths from the bundle
Add the folder at build time. The form is source:destination, with the destination relative to the bundle:
pyinstaller --onedir --console --add-data "assets:assets" main.py
PyInstaller 6 accepts the colon on every platform. On PyInstaller 5 and older the separator on Windows is a semicolon (--add-data "assets;assets"), which still works on Windows today. In a spec file the same thing is the datas list:
a = Analysis(
['main.py'],
datas=[('assets', 'assets')],
hiddenimports=[],
)
Then stop loading by bare relative path. Build every path from the bundle folder:
import os
import sys
def resource_path(*parts):
base = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base, *parts)
player = pygame.image.load(resource_path("assets", "player.png")).convert_alpha()
jump = pygame.mixer.Sound(resource_path("assets", "jump.ogg"))
font = pygame.font.Font(resource_path("assets", "PressStart2P.ttf"), 16)
sys._MEIPASS is the bundle folder PyInstaller sets at startup. In a onefile build it is a temporary folder the bootloader unpacks into. In a onedir build made with PyInstaller 6 it is the _internal folder next to the exe, which is where your assets folder now lives; older versions put everything beside the exe. The helper handles both, and falls back to the script’s folder when you run from source. Keep it in the main script or a top-level module, because __file__ in a subpackage points at that subpackage. The run-from-source version of this problem is covered in fixing FileNotFoundError for images and sounds.
Two Pygame details. The default font, pygame.font.Font(None, 24), is a file inside the pygame package (freesansbold); pygame 2 ships its own PyInstaller hook that collects it, along with the SDL DLLs on Windows that decode OGG and MP3, so upgrade pygame and PyInstaller before debugging a font or codec failure on old versions. And pygame.font.SysFont("somefont", 24) does not crash when the player’s machine lacks that font: it falls back to the default font. The text just looks different, so ship a .ttf and load it with Font.
Fix 2: stop using a console that is not there
Since PyInstaller 5.7, a windowed build on Windows leaves sys.stdout and sys.stderr set to None, the same as pythonw.exe. A plain print() is safe: Python skips it when there is no stdout. What raises is anything that calls a method on the missing object:
AttributeError: 'NoneType' object has no attribute 'write'
AttributeError: 'NoneType' object has no attribute 'flush'
RuntimeError: sys.stderr is None
RuntimeError: input(): lost sys.stdin
The first two come from sys.stdout.write(...), sys.stdout.flush() or a library that does the same (progress bars, colour output). The third is faulthandler.enable() with no file argument. The last is input(); newer Python versions shorten it to “lost sys.stdin”. This is the classic case of a game that works with --console and fails the moment you add --windowed.
Fix the calling code where it is yours. For libraries, PyInstaller’s documentation gives this workaround, placed at the very top of the entry script before other imports:
import os
import sys
if sys.stdout is None:
sys.stdout = open(os.devnull, "w")
if sys.stderr is None:
sys.stderr = open(os.devnull, "w")
Replace input() prompts with an in-game text field or a config file. Pass a real file to faulthandler.enable(file=...).
Fix 3: hidden imports and package data
If the traceback says a module of yours does not exist, PyInstaller never saw an import for it. Typical in games: levels, enemies or states loaded with importlib.import_module("levels." + name). Name them, or collect the package:
pyinstaller --hidden-import levels.level_03 main.py
pyinstaller --collect-submodules levels main.py
When a third-party package fails looking for its own data files or DLLs, --collect-all packagename collects its submodules, data files and binaries in one go. It makes the build bigger, so use it for the package named in the traceback, not for everything. Building with --debug=imports makes the frozen interpreter print every import, which shows the last one that worked.
Fix 4: write saves and logs to a per-user folder
A PermissionError or a save that vanishes between runs means you are writing inside the bundle. A onefile build unpacks to a new temporary folder each run and deletes it on exit, and a game installed under Program Files cannot write beside its exe. Write to the user’s data folder:
def user_data_dir(app="MyGame"):
if sys.platform == "win32":
root = os.getenv("APPDATA")
elif sys.platform == "darwin":
root = os.path.expanduser("~/Library/Application Support")
else:
root = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
path = os.path.join(root, app)
os.makedirs(path, exist_ok=True)
return path
The platformdirs package does the same with platformdirs.user_data_dir("MyGame", "MyStudio").
Fix 5: call freeze_support()
A frozen game that uses multiprocessing (a worker pool for pathfinding or level generation) and opens window after window, or dies at once, is missing one call. PyInstaller requires it on every platform, before any other multiprocessing use:
import multiprocessing
if __name__ == "__main__":
multiprocessing.freeze_support()
main()
Leave a crash log for players
Once the build works, make the next failure readable without a rebuild. Catch at the top level, save the traceback, tell the player where it is, and exit with sys.exit so they see your message and not the bootloader’s:
import traceback
if __name__ == "__main__":
try:
main()
except Exception:
log_path = os.path.join(user_data_dir(), "crash.log")
with open(log_path, "w", encoding="utf-8") as f:
f.write(traceback.format_exc())
if sys.platform == "win32":
import ctypes
ctypes.windll.user32.MessageBoxW(
None, "The game hit an error. Details were saved to:\n" + log_path,
"My Game", 0x10)
sys.exit(1)
A try block only covers the main thread’s call stack. For the rest, and for sending the traceback instead of saving it, see sys.excepthook for Pygame.
Similar failures that are not this error
- Built on a newer system than the player’s. PyInstaller bundles the Python you built with. Python 3.9 and later do not run on Windows 7, and 3.13 and later do not run on Windows 8.1; that fails while the bootloader loads Python, before your script runs. On Linux the bundle depends on the build machine’s glibc, so build on the oldest distribution you support. See version GLIBC not found and exporting a Pygame game for Linux.
- Antivirus. Onefile executables are a frequent false positive. If a scanner quarantines the exe or files in its temporary
_MEIfolder, the game fails to start or fails on an import that worked for you. A onedir build inside a zip or installer tends to draw fewer flags, and signing the executable helps. - No display. A traceback ending in
pygame.errorabout the video device is an environment problem, not a bundling one: see No available video device.
How to confirm the fix
Work in this order: get --onedir --console running from a terminal, then switch to --windowed and retest (this is where the stdout causes appear), then --onefile if you want a single file (this is where path and save-location causes appear). Change one flag per build so you know which one broke it.
Then copy the output to a machine or virtual machine with no Python installed, put it in a folder with a space in its name, and launch it by double-click and from a shortcut. A different working directory and a missing interpreter are the two things your own PC hides. Play past the first asset load of every type: an image, a sound, music and a font.
Getting the traceback from players automatically
The Bugnet Pygame SDK is plain Python, so PyInstaller freezes it into the build like any other import (pip install bugnet-sdk). bugnet_sdk.init(api_key) installs an exception hook that files the traceback as a report and flushes the upload before Python exits. The hook runs before the bootloader shows its dialog, so the report arrives with the OS, hardware and game version attached even when the player closes the dialog and never writes to you. Call bugnet_sdk.report_error(message, stack) from a top-level except block like the one above if you handle the crash yourself. Reports with the same title stack into one entry with a count, so a missing asset hit by fifty players is one line. It cannot help when the process never reaches your script: a quarantined exe or a Python DLL that will not load on Windows 7 sends nothing. Setup is in the SDK docs.
Related guides
- Python sys.excepthook for Pygame: Catch and Report Every Unhandled Exception
- How to Fix “FileNotFoundError” for Images and Sounds in Pygame (Working Directory Problems)
- How to Fix “pygame.error: No available video device” in Pygame
- How to Export a Pygame Game for Linux
- How to Fix “version GLIBC_2.34 not found” for Your Linux Game
Frequently asked questions
What does Failed to execute script main mean in PyInstaller?
Your Python code raised an exception that nothing caught, and the PyInstaller bootloader is reporting that the script ended with an error. The message names your entry script, not the cause. Build with a console and run the exe from a terminal to read the real traceback.
Why does my Pygame game work with python main.py but fail as an exe?
The frozen build only contains what PyInstaller could see. Images, sounds and fonts are not bundled unless you pass add-data, relative paths resolve against the launch folder instead of the bundle, and a windowed build has no stdout. Any of those raises an exception that never happens from source.
How do I see the error in a PyInstaller windowed build?
On PyInstaller 4.4 and later the Windows dialog includes the traceback in a scrollable box. Otherwise rebuild without the windowed option and run the exe from an open terminal, or wrap your entry point in try and except and write traceback.format_exc() to a log file.
Where do bundled files go in PyInstaller 6?
In a onedir build everything except the executable is placed in a folder named _internal next to it, and sys._MEIPASS points at that folder. In a onefile build the files are unpacked to a temporary folder at launch, and sys._MEIPASS points there instead.
Is the add-data separator a colon or a semicolon?
Use source:destination with a colon. PyInstaller 6 accepts the colon on every platform. On PyInstaller 5 and older, Windows needed a semicolon, and the semicolon form still works on Windows in current versions.
The dialog names the messenger. Build onedir with a console, read the last line of the traceback, and fix that one thing before adding windowed or onefile back.