Python scriptleri için sıfır-ayar olay yeri inceleme ve hata raporlama aracı.
Project description
Blackbox 🔲
A zero-configuration, post-mortem state recorder and crash reporter for Python.
Overview
When developing complex Python applications—especially long-running numerical simulations, data processing pipelines, or unattended scripts—a standard terminal traceback is rarely enough. Standard tracebacks tell you where your code crashed, but they completely fail to tell you why.
You are often left wondering: What were the exact values of the local variables when the division by zero occurred? What was the state of the iteration index? Blackbox is designed to solve this exact problem.
Think of Blackbox as a flight recorder for your Python functions. By simply wrapping your core functions with a single decorator, Blackbox lies dormant with zero performance overhead during normal execution. However, the exact millisecond an unhandled exception occurs, Blackbox intercepts the crash, extracts the precise state of all local variables in the failing frame, and dumps this invaluable context into a clean, offline HTML report.
Core Mechanisms & Philosophy
Blackbox is built on the principle of maximum utility with minimum interference.
- Zero-Overhead Execution: Unlike traditional debuggers (like
pdb) or profilers that continuously monitor state and slow down your code, Blackbox does not trace loops or evaluate variables during normal execution. Your heavy calculations and loops run at full native speed. Performance is absolutely unaffected until an actual exception is raised. - Surgical State Capture: Upon a crash, the system uses
sys.exc_info()to traverse the traceback stack. It pinpoints the exact frame where the exception originated and extracts the local variables, arguments, and object states exactly as they were at the moment of failure. - Safe Serialization (
safe_repr): Long-running scripts often deal with massive data structures, large arrays, or unreadable components (such as open serial ports, database connections, or unpicklable objects). Blackbox employs a custom sanitization module to safely truncate enormous objects. This guarantees that the crash reporter itself will never cause a secondaryMemoryErroror recursive loop while trying to save the state. - Offline, Self-Contained Reporting: There are no API keys, no cloud telemetry, and no external servers. A self-contained HTML file is generated locally in the
crash_reportsdirectory. The UI automatically highlights suspicious variable states (such as0,None, empty lists[], orFalse) that typically cause systemic crashes. - Standard Termination: Blackbox does not swallow your errors. After the HTML report is successfully written to the disk, the original exception is faithfully re-raised. This ensures your program terminates natively or can be caught by upper-level exception handlers.
Installation
Install directly from PyPI:
pip install blackbox-py
Usage & Real-World Example
Wrap your function with the @blackbox decorator. No configuration, initialization, or setup functions are required.
Basic Example
from blackbox import blackbox
@blackbox
def run_heavy_simulation(battery_id, max_cycles):
print(f"Starting simulation for {battery_id}")
for cycle in range(max_cycles):
# Complex calculations happening here...
current = 10 - cycle
voltage = 120.5
# At cycle 10, current becomes 0. A standard traceback wouldn't
# tell you that 'cycle' was exactly 10 when this failed.
# Blackbox will capture the exact state of 'current', 'voltage', and 'cycle'.
resistance = voltage / current
return True
run_heavy_simulation("LFP-BATT-01", 15)
What Happens When It Crashes?
- The script will raise the
ZeroDivisionErroras it normally would. - A new directory called
crash_reportswill be instantly created in your working directory. - An HTML file named with the current timestamp (e.g.,
crash_run_heavy_simulation_20260718_121825.html) will be generated. - Opening this HTML file will reveal the exact line of code that failed, alongside a clean table showing:
battery_id:"LFP-BATT-01"max_cycles:15cycle:10current:0(Highlighted in red as a suspicious value)voltage:120.5
API Reference & Usage Guide
The Blackbox library is designed to be completely plug-and-play. You do not need to write custom error handlers or modify your core logic.
@blackbox
What does it do?
This is the core decorator of the library. It acts as a wrapper around any function. During normal operation, it does nothing and has zero impact on performance. If (and only if) an unhandled exception occurs inside the wrapped function, it intercepts the crash, reads the state of all local variables at that exact moment, generates the HTML report, and then re-raises the error.
How to use it:
Simply import it and place it directly above the function you want to monitor. It requires no arguments.
from blackbox import blackbox
@blackbox
def process_sensor_data(sensor_id, readings):
# If anything in this function fails, Blackbox will generate a report.
multiplier = 0
result = readings[0] / multiplier # Crash happens here
return result
What do you need to write to catch an error?
Nothing. You do not need to write try-except blocks. Blackbox automatically catches native Python errors (like ZeroDivisionError, IndexError, TypeError, etc.).
It also catches manual errors raised by the developer. If your script logic dictates a failure, simply use Python's standard raise statement:
from blackbox import blackbox
@blackbox
def connect_to_database(retries):
connection_status = False
if retries == 0:
# Manually triggering a crash. Blackbox will catch this,
# save the state showing 'retries = 0' and 'connection_status = False',
# and generate the HTML report.
raise ConnectionError("Failed to connect after all retries.")
Security & Privacy Warning
Blackbox captures the exact values of all local variables at the time of a crash. This means if you have hardcoded passwords, API keys, or sensitive database URIs present in the failing function, they will be written in plain text to the HTML report.
- Always add
crash_reports/to your.gitignorefile. - Never share these HTML reports on public forums without reviewing them for sensitive data first.
Under the Hood (Developer Documentation)
Blackbox is modular by design. If you want to contribute or just understand how the magic happens, here is a breakdown of the internal architecture:
1. core.py (The Interceptor)
This is the heart of the library. It contains the @blackbox decorator.
- Mechanism: It wraps the target function inside a barebones
try-exceptblock. During normal execution, it simply returns the function's original output. - Crash Handling: If an exception is caught, it uses Python's built-in
sys.exc_info()to grab the active traceback object. It navigates to the exact frame where the error originated (tb.tb_next) and extracts the local variable dictionary (frame.f_locals). It then passes this raw data to the reporter before finally re-raising the original exception.
2. utils.py (The Sanitizer)
Dumping raw memory into a string is dangerous. If your local variables contain a 10,000-element list, a raw database connection pool, or deeply nested dictionaries, a naive string conversion will cause a secondary MemoryError or recursion limit crash.
- Mechanism: The
safe_repr(obj)function inspects every extracted variable. It safely truncates large iterables (e.g., showing only the first and last few elements of a list), limits string lengths, and handles unpicklable or complex objects gracefully. This guarantees Blackbox will never crash your system while trying to report a crash.
3. reporter.py (The Visualizer)
This module is responsible for turning the sanitized variables and traceback data into a human-readable format.
- Mechanism: It dynamically generates an offline HTML file. The reporter iterates through the sanitized local variables and applies a simple heuristic check: if a variable's value is
0,None,[], orFalse, it flags it visually in the HTML report. This helps developers instantly spot the "empty" or "null" states that typically lead toZeroDivisionErrororTypeErrorcrashes.
Project Structure
For developers looking to contribute or understand the source code:
core.py: Contains the main@blackboxdecorator and exception interception logic.reporter.py: Handles the generation and formatting of the HTML output.utils.py: Contains thesafe_reprfunction and data sanitization algorithms.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file blackbox_py_custom-0.1.1.tar.gz.
File metadata
- Download URL: blackbox_py_custom-0.1.1.tar.gz
- Upload date:
- Size: 8.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
481750e9458c28037af63ab2b7534e24d6d844f1eb73638ee9f6a5aac71437bb
|
|
| MD5 |
057ec5e8ecbc0ca91f51a31b003a5a48
|
|
| BLAKE2b-256 |
0b9f2ae367ca9c0e768cb376257c88412d08b725023753a47b7dfbe585daa35c
|
File details
Details for the file blackbox_py_custom-0.1.1-py3-none-any.whl.
File metadata
- Download URL: blackbox_py_custom-0.1.1-py3-none-any.whl
- Upload date:
- Size: 9.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4846bf8a00da2617c4fe87cd31cbddfece3f0657898e5ee6f027cf351af7c6d5
|
|
| MD5 |
d19251dc6c0df33e86b24a86efaea5c1
|
|
| BLAKE2b-256 |
2225691685f717268522e819066ed6cb2c69a1116a1347e759bed105c4650452
|