From 4d943e9dbb6fe9c99eabeb2d4649f3eaac002c55 Mon Sep 17 00:00:00 2001 From: Ram Rachum Date: Wed, 24 Apr 2019 22:28:43 +0300 Subject: [PATCH] Implement IPython code fetching --- pysnooper/tracer.py | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/pysnooper/tracer.py b/pysnooper/tracer.py index 2002fd3..62b7a2f 100644 --- a/pysnooper/tracer.py +++ b/pysnooper/tracer.py @@ -15,6 +15,7 @@ import itertools import six MAX_VARIABLE_LENGTH = 100 +ipython_filename_pattern = re.compile('^$') def get_shortish_repr(item): @@ -79,11 +80,23 @@ def get_source_from_frame(frame): if source is not None: source = source.splitlines() if source is None: - try: - with open(file_name, 'rb') as fp: - source = fp.read().splitlines() - except (OSError, IOError): - pass + ipython_filename_match = ipython_filename_pattern.match(file_name) + if ipython_filename_match: + entry_number = int(ipython_filename_match.group(1)) + try: + import IPython + ipython_shell = IPython.get_ipython() + ((_, _, source_chunk),) = ipython_shell.history_manager. \ + get_range(0, entry_number, entry_number + 1) + source = source_chunk.splitlines() + except Exception: + pass + else: + try: + with open(file_name, 'rb') as fp: + source = fp.read().splitlines() + except (OSError, IOError): + pass if source is None: source = UnavailableSource()