From cb56d19d82b8d5a9b606ba909bb716868704b5ab 2012-07-03 21:53:44 From: Bradley M. Froehle Date: 2012-07-03 21:53:44 Subject: [PATCH] %prun: Restore `stats.stream` after running `print_stream`. When profiling, the output from `print_stream` is captured so that the output can be paged. To do so, the `stream` attribute is set to a `StringIO` object but was not restored after the output was captured. As a result, the stats object returned by `%prun -r` did not display any output when calling its `print_stream` method. In addition, the `pstats.Stats` class has the `stream` attribute for all currently supported Python versions, so the extra branch of code can be removed. --- diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py index e111873..9b5c2e0 100644 --- a/IPython/core/magics/execution.py +++ b/IPython/core/magics/execution.py @@ -226,20 +226,12 @@ python-profiler package from non-free.""") # Trap output. stdout_trap = StringIO() - - if hasattr(stats,'stream'): - # In newer versions of python, the stats object has a 'stream' - # attribute to write into. + stats_stream = stats.stream + try: stats.stream = stdout_trap stats.print_stats(*lims) - else: - # For older versions, we manually redirect stdout during printing - sys_stdout = sys.stdout - try: - sys.stdout = stdout_trap - stats.print_stats(*lims) - finally: - sys.stdout = sys_stdout + finally: + stats.stream = stats_stream output = stdout_trap.getvalue() output = output.rstrip()