From 8b789ce21eb8a2c3bc3fe3f80d7a05ec0b653d5c 2012-01-12 21:43:28 From: Thomas Kluyver Date: 2012-01-12 21:43:28 Subject: [PATCH] Find .py files for verbose tracebacks, rather than trying to tokenize .pyc files. --- diff --git a/IPython/core/ultratb.py b/IPython/core/ultratb.py index f06a172..2fbe859 100644 --- a/IPython/core/ultratb.py +++ b/IPython/core/ultratb.py @@ -100,6 +100,7 @@ from IPython.core.excolors import exception_colors from IPython.utils import PyColorize from IPython.utils import io from IPython.utils import py3compat +from IPython.utils import pyfile from IPython.utils.data import uniq_stable from IPython.utils.warn import info, error @@ -873,6 +874,8 @@ class VerboseTB(TBTools): tokeneater.name_cont = False def linereader(file=file, lnum=[lnum], getline=linecache.getline): + if file.endswith(('.pyc','.pyo')): + file = pyfile.source_from_cache(file) line = getline(file, lnum[0]) lnum[0] += 1 return line diff --git a/IPython/utils/pyfile.py b/IPython/utils/pyfile.py new file mode 100644 index 0000000..bedecd6 --- /dev/null +++ b/IPython/utils/pyfile.py @@ -0,0 +1,23 @@ +"""Utilities for working with Python source files. + +Exposes various functions from recent Python standard libraries, along with +equivalents for older Python versions. +""" +import os.path + +try: # Python 3.2 + from imp import source_from_cache, cache_from_source +except ImportError: + # Python <= 3.1: .pyc files go next to .py + def source_from_cache(path): + basename, ext = os.path.splitext(path) + if ext not in {'.pyc', '.pyo'}: + raise ValueError('Not a cached Python file extension', ext) + # Should we look for .pyw files? + return basename + '.py' + + def cache_from_source(path, debug_override=None): + if debug_override is None: + debug_override = __debug__ + basename, ext = os.path.splitext(path) + return basename + '.pyc' if debug_override else '.pyo'