PySnooper
PySnooper is a Python debugging tool often described as a 'poor man's debugger'. It allows developers to trace the execution of their code by automatically logging variable values, function calls, and execution lines to stdout or a file, without requiring traditional breakpoints or extensive manual print statements. The current stable version is 1.2.3. Recent GitHub activity indicates ongoing maintenance, including support for newer Python versions.
Warnings
- gotcha PySnooper can introduce noticeable performance overhead, especially in performance-critical sections or with extensive loops/execution. This is due to the detailed logging and introspection it performs.
- gotcha For complex functions, deep call stacks, or extensive loops, PySnooper's output can become extremely verbose and difficult to parse. This might make it harder to find the relevant debugging information amidst a large volume of logs.
- gotcha When redirecting PySnooper's output to a file, the default colored output (ANSI escape codes) can make the log file unreadable in standard text editors. These escape codes are meant for terminal display.
- breaking PySnooper is designed for debugging and is not suitable for production environments. Leaving it enabled can expose internal state, negatively impact performance, and fill disk space with logs. It also adds a dependency that is only useful during development.
Install
-
pip install pysnooper
Imports
- snoop
import pysnooper @pysnooper.snoop() def my_function(): pass
Quickstart
import pysnooper
import os
# To demonstrate file output, create a dummy log file path
log_file_path = os.path.join(os.getcwd(), 'pysnooper_output.log')
@pysnooper.snoop(output=log_file_path, color=False)
def number_to_bits(number):
if number == 0:
return [0]
bits = []
while number:
number, remainder = divmod(number, 2)
bits.insert(0, remainder)
return bits
result = number_to_bits(6)
print(f"Result for 6: {result}")
# You can also use it as a context manager for a block of code
def main_logic():
a = 10
b = 20
with pysnooper.snoop(output=log_file_path, color=False):
temp = a + b
final = temp * 2
print(f"Final value in main_logic: {final}")
main_logic()
# Cleanup (optional, for a runnable example)
# import os
# if os.path.exists(log_file_path):
# os.remove(log_file_path)