在IPython中分页stdout输出

时间:2017-10-26 09:49:04

标签: ipython stdout

是否可以在(交互式)IPython会话中通过寻呼机传递stdout输出,例如less?如果是这样,怎么样?

例如,在

In [1]: from some_module import function_that_prints_a_lot

In [2]: function_that_prints_a_lot()

... everything scrolls away ...

我想浏览stdout的{​​{1}}输出。

另一个例子:

function_that_prints_a_lot

我查看了IPython magic commands,但未找到任何解决方案。

2 个答案:

答案 0 :(得分:4)

正如聊天中所讨论的,没有简单的方法可以做到这一点。由于该函数打印了值,因此您唯一能做的就是捕获输出+然后页面输出。关于你可能感兴趣的jupyter的问题很少

https://github.com/jupyter/notebook/issues/2049

https://github.com/ipython/ipython/issues/6516

捕获输出

输出捕获可以多种方式完成

1。重载打印方法

import sys
data = ""
def myprint(value, *args, sep=' ', end='\n', file=sys.stdout, flush=False):
    global data
    current_text = value + " ".join(map(str, args)) + "\n"
    data += current_text

original_print = print
print = myprint

def testing():
    for i in range(1,1000):
        print ("i =", i)

testing()

original_print("The output from testing function is", data)

2。使用StringIO

捕获输出
from cStringIO import StringIO
import sys

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        del self._stringio    # free up some memory
        sys.stdout = self._stdout

用法:

with Capturing() as output:
    do_something(my_object)

3。使用redirect_stdout

捕获输出
import io
from contextlib import redirect_stdout

f = io.StringIO()
with redirect_stdout(f):
    do_something(my_object)
out = f.getvalue()

4。使用%% capture magic命令

进行捕获

Capture magic

分页输出

您可以使用magin %page

%page -r <variablename>

https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-page

或者您可以使用Ipython代码

from IPython.core import page
page.page(variable)

有关详细信息,请参阅以下

PS:一些有用的线程

How to capture stdout output from a Python function call?

How can I redirect print output of a function in python

https://github.com/ipython/ipython/wiki/Cookbook:-Sending-built-in-help-to-the-pager

overload print python

答案 1 :(得分:1)

使用来自各种来源的点点滴滴,但基本上来自IPython官方文档中的IPython's cookbookDefining custom magics

In [1]: from IPython.core.magic import register_line_magic

In [2]: @register_line_magic
   ...: def my_pager(line):
   ...:     "my line magic"
   ...:     import io
   ...:     from IPython.core import page
   ...:     from contextlib import redirect_stdout
   ...:     f = io.StringIO()
   ...:     with redirect_stdout(f):
   ...:         eval(line)
   ...:     page.pager_page(f.getvalue())
   ...: del my_pager # don't pollute my namespace    

In [3]: def pippo(): print('\n'.join(str(i)for i in range(80)))

In [4]: %my_pager pippo()

这种方法有一个严重的缺点:如果作为%my_pager的参数的函数调用返回一个值,则表示该值丢失(不,%mypager result=print_and_return()将不起作用...)