Quick answer: Assign a function taking (exc_type, exc_value, exc_traceback) to sys.excepthook. Inside it, format the traceback with traceback.format_exception, POST it with urllib.request and a short timeout, then call the previous hook so the traceback still prints. Send synchronously, because the process exits as soon as the hook returns. Add threading.excepthook for worker threads and faulthandler for crashes in native code, since sys.excepthook sees neither.
A Pygame game that hits an unhandled exception closes its window and prints a traceback to a console the player does not have. In a packaged build there is no console at all. What reaches you is a message saying the game “just closed”. Python gives you one function that runs between the exception and the exit: sys.excepthook. This guide shows how to use it as a Pygame crash handler that sends the traceback to a server, where it stops short, and the three other hooks that cover what it misses.
- What sys.excepthook is and when Python calls it
- A sys.excepthook that sends the traceback to a server
- Send before the process exits
- Titles that group instead of scatter
- The hook versus a try/except around the main loop
- What sys.excepthook never sees
- Hard crashes in native code: faulthandler
- Frozen builds: PyInstaller and certificates
- What the Bugnet Pygame SDK installs for you
- Related guides
- Frequently asked questions
What sys.excepthook is and when Python calls it
When an exception propagates out of the last frame of the main thread, the interpreter calls:
sys.excepthook(exc_type, exc_value, exc_traceback)
The default implementation prints the familiar “Traceback (most recent call last)” text to sys.stderr. After the hook returns, the interpreter shuts down. You replace it by assigning your own function with the same three parameters. The original stays available as sys.__excepthook__.
Three things to know before writing one:
- It is the last thing that runs. You cannot resume the game from it. Its job is to record what happened.
SystemExitnever reaches it.sys.exit()and closing the window normally do not trigger the hook.KeyboardInterruptdoes, so pass Ctrl+C through without reporting it.- It only covers the main thread. Worker threads, asyncio tasks and crashes in C code have their own paths, covered below.
A sys.excepthook that sends the traceback to a server
Save this as crash_report.py next to your game. It uses only the standard library and Pygame. The endpoint and field names are Bugnet’s public submit API, and the shape is the same for any HTTP endpoint of your own.
import json
import os
import platform
import sys
import threading
import traceback
import urllib.request
import pygame
URL = "https://api.bugnet.io/api/bugs/submit"
API_KEY = "sk_live_your_project_key"
GAME_VERSION = "1.0.3"
_STDLIB = os.path.dirname(os.__file__)
_previous_hook = sys.excepthook
_previous_thread_hook = threading.excepthook
def _type_name(exc_type):
if exc_type.__module__ in ("builtins", "__main__"):
return exc_type.__qualname__
return exc_type.__module__ + "." + exc_type.__qualname__
def _stable_title(exc_type, tb):
where = ""
for frame in reversed(traceback.extract_tb(tb)):
own_code = ("site-packages" not in frame.filename
and not frame.filename.startswith(_STDLIB))
if own_code:
where = "%s:%d" % (os.path.basename(frame.filename), frame.lineno)
break
name = _type_name(exc_type)
return "%s at %s" % (name, where) if where else name
def post_report(title, description, timeout=5):
payload = {
"title": title[:300],
"description": description[-50000:],
"category": "crash",
"priority": "critical",
"platform": sys.platform,
"game_version": GAME_VERSION,
"os_info": platform.platform()[:100],
"device_info": "Python %s, pygame %s" % (
platform.python_version(), pygame.version.ver),
"auto_captured": True,
}
request = urllib.request.Request(
URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", "X-API-Key": API_KEY},
method="POST",
)
try:
urllib.request.urlopen(request, timeout=timeout).close()
return True
except Exception:
return False # the reporter must never raise from inside a hook
def send_crash(exc_type, exc_value, tb):
text = "".join(traceback.format_exception(exc_type, exc_value, tb))
return post_report(_stable_title(exc_type, tb), text)
def _crash_hook(exc_type, exc_value, tb):
if not issubclass(exc_type, KeyboardInterrupt):
send_crash(exc_type, exc_value, tb)
_previous_hook(exc_type, exc_value, tb)
def _thread_hook(args):
if args.exc_type is not SystemExit:
send_crash(args.exc_type, args.exc_value, args.exc_traceback)
_previous_thread_hook(args)
def install():
sys.excepthook = _crash_hook
threading.excepthook = _thread_hook
Call crash_report.install() as the first line of your entry point, before pygame.init(), so a failure during start-up is covered too.
Two habits in that code are worth copying. It saves the hook that was there before and calls it afterwards, so the traceback still prints during development and any other tool that installed a hook keeps working. And the whole send is wrapped in a broad except, because an exception raised inside the hook replaces the report you were trying to make with a confusing second traceback.
Send before the process exits
The most common reason a Python crash reporter “works on my machine and never in production” is threading. It is natural to hand the HTTP request to a background thread so nothing blocks. In a hook that is exactly wrong: when the hook returns, the interpreter begins shutting down, and daemon threads are killed mid-request.
The fix is to do the request in the hook itself, as above. The window is already frozen, so nobody notices a blocking call. Keep the timeout short. Five seconds is enough for a healthy connection and bounded for a player who is offline. If you prefer a thread, make it a non-daemon one, which the interpreter waits for before exiting.
If the player is offline the report is lost. To keep it, write the same text to a file in your save folder when post_report returns False, and send any file you find there at the next start-up.
Titles that group instead of scatter
The title decides whether five hundred copies of one crash appear as one issue with a count or as five hundred issues. Bugnet stacks a report onto an existing one when the title matches exactly, and most trackers group on something similar.
str(exc_value) is a bad title because messages carry data: KeyError: 'sword_4812', a file path with the player’s username, a list index. _stable_title uses two things that do not change between players: the exception class and the innermost frame that belongs to your code, skipping the standard library and installed packages. A crash inside json.loads is then filed against your save.py:88, which is where you will fix it.
The class name needs care in Pygame. pygame.error.__name__ is just error, so a title built from __name__ alone reads “error at render.py:40”. _type_name adds the module for anything that is not a builtin, giving pygame.error. One trade-off: a line number changes when you edit the file, so the same bug gets a new title in the next release. If you would rather group across versions, use frame.name, the function name, in place of the line number.
The hook versus a try/except around the main loop
The hook fires after your code has unwound. The display surface may still exist, but your game objects are out of reach, and all you can do is report. A try around the main loop catches the same exceptions one step earlier, while you can still save the game and tell the player something useful.
import sys
import pygame
import crash_report
def show_crash_screen(message):
screen = pygame.display.get_surface()
if screen is None:
return
font = pygame.font.Font(None, 30)
screen.fill((18, 22, 34))
screen.blit(font.render(message, True, (255, 255, 255)), (40, 40))
screen.blit(font.render("Press any key to close.", True, (170, 180, 200)), (40, 84))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type in (pygame.QUIT, pygame.KEYDOWN):
return
pygame.time.wait(50)
def main():
pygame.init()
screen = pygame.display.set_mode((1280, 720))
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# update and draw the game here
pygame.display.flip()
clock.tick(60)
if __name__ == "__main__":
crash_report.install()
try:
main()
except Exception:
exc_type, exc_value, tb = sys.exc_info()
sent = crash_report.send_crash(exc_type, exc_value, tb)
sys.__excepthook__(exc_type, exc_value, tb)
show_crash_screen("The game hit an error. " +
("A report was sent." if sent else "No report could be sent."))
finally:
pygame.quit()
Catch Exception, not a bare except, so SystemExit and KeyboardInterrupt still end the program normally. Because the exception is handled here, sys.excepthook does not also fire, so there is no double report. Keep install() anyway. It is the backstop for errors raised outside main(), such as a failing import, and it is what sets the thread hook.
What sys.excepthook never sees
Threads. If your asset loader or save writer runs in a threading.Thread and raises, the thread dies and the main loop keeps running. The player sees a loading bar that never finishes. From Python 3.8 those exceptions go to threading.excepthook, which receives one argument with exc_type, exc_value, exc_traceback and thread attributes. The module above installs it alongside the main hook.
asyncio tasks. This matters if you use asyncio for networking, or package for the browser with pygbag, where the main loop is an async def main(). An exception inside main() itself propagates out of asyncio.run() and reaches sys.excepthook as usual on desktop. An exception inside a task you started with create_task() and never awaited does not. It goes to the loop’s exception handler:
def _asyncio_handler(loop, context):
exc = context.get("exception")
if exc is not None:
crash_report.send_crash(type(exc), exc, exc.__traceback__)
loop.default_exception_handler(context)
# inside async def main():
asyncio.get_running_loop().set_exception_handler(_asyncio_handler)
In a browser build the standard library’s networking is restricted, so test the reporting path there separately instead of assuming urllib behaves as it does on desktop.
Unraisable exceptions. Errors raised inside __del__ methods and garbage collection callbacks cannot propagate anywhere. Python passes them to sys.unraisablehook, also from 3.8. They are rarely the cause of a crash, but they are worth logging.
Hard crashes in native code: faulthandler
Pygame is a thin layer over SDL, and a segmentation fault inside SDL, a driver or another C extension ends the process without raising a Python exception. No hook runs. The standard library’s faulthandler module handles this case: it installs low-level handlers that write the Python stack of every thread to a file descriptor at the moment of the fault.
import faulthandler
import os
import crash_report
FAULT_LOG = os.path.join(os.path.expanduser("~"), ".mygame_fault.log")
_fault_file = None
def install_faulthandler():
global _fault_file
try:
with open(FAULT_LOG, "r", encoding="utf-8", errors="replace") as f:
previous = f.read().strip()
except OSError:
previous = ""
if previous:
first_line = previous.splitlines()[0][:100]
crash_report.post_report("Hard crash in previous run: " + first_line, previous)
_fault_file = open(FAULT_LOG, "w") # truncates; must stay open
faulthandler.enable(file=_fault_file, all_threads=True)
The file is empty after a clean run. After a hard crash it holds a line such as Fatal Python error: Segmentation fault followed by the Python frames that were executing, which tells you which of your calls into Pygame was on the stack. The process cannot send anything while it is dying, so the report goes out the next time the game starts. Keep a reference to the file object for the life of the program. If it is garbage collected, the handler writes to a closed descriptor.
Frozen builds: PyInstaller and certificates
Everything above matters most in the build players actually run.
- No console. A PyInstaller build made with
--windowedhas no terminal, andsys.stderrmay beNone. Depending on the platform and PyInstaller version, the player gets a terse “Failed to execute script” dialog or nothing at all. In neither case does the traceback reach you unless your hook sends or saves it. - Certificates. If reports arrive from your development machine but never from a packaged build, look for
CERTIFICATE_VERIFY_FAILED. Some Python distributions and frozen apps cannot find a CA bundle for HTTPS. The usual remedy is to bundle thecertifipackage and passcontext=ssl.create_default_context(cafile=certifi.where())tourlopen. Temporarily log the exception inpost_reportto confirm that this is the cause before changing anything. - Test the real thing. Add a hidden key that raises an exception on purpose, build the game, run it on a machine without Python installed, and check that the report shows up.
What the Bugnet Pygame SDK installs for you
The Bugnet Pygame SDK (pip install bugnet-sdk, or one file next to your game) sets this same hook. bugnet_sdk.init(api_key) saves the current sys.excepthook and installs its own. On an unhandled exception it files a report with the full traceback, the recent lines your game printed, a screenshot of the display surface, and the OS, device and game version, then calls the previous hook so the traceback still prints. bugnet_sdk.shutdown() puts the original hook back. Repeats of the same message within 30 seconds are sent once.
The SDK sends on background threads so the game loop never blocks, and it handles the shutdown problem described above with a bounded wait: after filing the report, the hook waits up to five seconds for the upload to finish before the process ends (in bugnet-sdk 1.1.1 and later). Ctrl+C is passed through without a report. If you run your own crash screen from the main-loop pattern above, call bugnet_sdk.report_error(str(exc), traceback.format_exc()) in the except block, and bugnet_sdk.shutdown() on the way out waits for anything still being sent. The same SDK draws an in-game report form for bugs players describe themselves. Reports land in a dashboard where matching titles stack with an occurrence count. The free plan covers one project and up to 100 bug reports in total, and the SDK docs have the full setup.
Related guides
- How to Add an In-Game Bug Report Screen to a Pygame Game
- How to Debug a Production Crash in a Pygame Game
- 5 Common Pygame Crashes and How to Fix Them
- How to Fix “pygame.error: display Surface quit” in Pygame
- How to Set Up Crash Reporting in Pygame for Windows
Frequently asked questions
What is sys.excepthook in Python?
It is the function Python calls with the exception type, value and traceback when an exception reaches the top of the main thread without being caught. The default prints the traceback to stderr. Assign your own function to sys.excepthook to log or report the error first.
How do I catch all exceptions in a Pygame game?
Wrap the main loop in try and except Exception so you can report the error and show the player a message while the window still exists, and set sys.excepthook as a backstop for anything raised outside it. Add threading.excepthook for worker threads and faulthandler for crashes inside native code.
Does sys.excepthook catch exceptions in threads?
No. An exception that escapes a threading.Thread goes to threading.excepthook, available from Python 3.8. Set both hooks. The main thread keeps running after a worker thread dies, so without the second hook the game just stops loading or saving with no visible error.
Why does my crash report never arrive when I send it from a thread?
Because the process is exiting. After the hook returns Python shuts down and daemon threads are killed without finishing. Send the request synchronously inside the hook with a short timeout, or use a non-daemon thread so the interpreter waits for it.
How do I see the traceback from a PyInstaller windowed build?
You do not, by default. A windowed build has no console, so the traceback has nowhere to go and the player sees a terse dialog or nothing. Write it to a file in your save folder or send it to a server from sys.excepthook.
The hook runs once, at the very end. Send the report synchronously, call the previous hook, and cover threads and hard crashes separately, because the hook never sees them.