PySnooper/pysnooper/pysnooper.py

77 lines
1.9 KiB
Python
Raw Normal View History

2019-04-19 22:20:27 +00:00
# Copyright 2019 Ram Rachum.
# This program is distributed under the MIT license.
import sys
import os
import inspect
import types
import datetime as datetime_module
import re
import collections
import decorator
from . import utils
2019-04-21 13:53:18 +00:00
from . import pycompat
from .tracer import Tracer
2019-04-19 22:20:27 +00:00
2019-04-21 18:39:32 +00:00
2019-04-21 13:53:18 +00:00
def get_write_function(output):
2019-04-19 22:20:27 +00:00
if output is None:
def write(s):
stderr = sys.stderr
stderr.write(s)
2019-04-21 13:53:18 +00:00
elif isinstance(output, (pycompat.PathLike, str)):
2019-04-19 22:20:27 +00:00
def write(s):
2019-04-22 12:10:34 +00:00
with open(output, 'a') as output_file:
2019-04-19 22:20:27 +00:00
output_file.write(s)
else:
assert isinstance(output, utils.WritableStream)
def write(s):
output.write(s)
2019-04-21 18:39:32 +00:00
2019-04-19 22:20:27 +00:00
return write
2019-04-21 18:39:32 +00:00
2019-04-19 22:20:27 +00:00
2019-04-21 18:35:43 +00:00
def snoop(output=None, variables=(), depth=1, prefix=''):
2019-04-22 09:05:42 +00:00
'''
Snoop on the function, writing everything it's doing to stderr.
This is useful for debugging.
When you decorate a function with `@pysnooper.snoop()`, you'll get a log of
every line that ran in the function and a play-by-play of every local
variable that changed.
If stderr is not easily accessible for you, you can redirect the output to
a file::
@pysnooper.snoop('/my/log/file.log')
See values of some variables that aren't local variables::
@pysnooper.snoop(variables=('foo.bar', 'self.whatever'))
Show snoop lines for functions that your function calls::
@pysnooper.snoop(depth=2)
Start all snoop lines with a prefix, to grep for them easily::
@pysnooper.snoop(prefix='ZZZ ')
'''
2019-04-19 22:20:27 +00:00
write = get_write_function(output)
@decorator.decorator
2019-04-21 13:53:18 +00:00
def decorate(function, *args, **kwargs):
2019-04-19 22:20:27 +00:00
target_code_object = function.__code__
2019-04-21 13:53:18 +00:00
with Tracer(target_code_object=target_code_object,
write=write, variables=variables,
2019-04-21 18:35:43 +00:00
depth=depth, prefix=prefix):
2019-04-19 22:20:27 +00:00
return function(*args, **kwargs)
2019-04-21 18:39:32 +00:00
2019-04-19 22:20:27 +00:00
return decorate
2019-04-21 18:39:32 +00:00