Skip to content

Instantly share code, notes, and snippets.

@Winand
Created March 25, 2025 13:23
Show Gist options
  • Save Winand/74b3ff99517fec3f09f41d5271685da6 to your computer and use it in GitHub Desktop.
Save Winand/74b3ff99517fec3f09f41d5271685da6 to your computer and use it in GitHub Desktop.
Decorator which re-runs a function if it exited with a specified code
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from sys import _ExitCode
def exit_retry(tries: int, code: "_ExitCode | None" = None, pause: float = 0):
"""Retry function call after sys.exit().
:param retries: number of retries
:type retries: int
:param code: exit code to trigger retry (None=any)
:type code: str | int | None
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
last_code: _ExitCode = None
for i in range(tries):
try:
if i: # pause between iterations
print(f"Retry after {pause}s...")
sleep(pause)
return func(*args, **kwargs)
except SystemExit as e:
last_code = e.code
if not code or e.code == code:
continue
raise
sys.exit(last_code)
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment