在IPython中分页stdout输出

Ale*_*xey 6 stdout ipython

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

例如,在

In [1]: from some_module import function_that_prints_a_lot

In [2]: function_that_prints_a_lot()

... everything scrolls away ...
Run Code Online (Sandbox Code Playgroud)

我想翻阅stdout输出function_that_prints_a_lot.

另一个例子:

In [1]: %run script_that_prints_a_lot.py
Run Code Online (Sandbox Code Playgroud)

我查看了IPython 魔术命令,但没有找到任何解决方案.

Tar*_*ani 6

正如聊天中所讨论的那样,没有简单的方法可以做到这一点。由于该函数打印值,因此您唯一可以做的就是捕获输出 + 然后页面输出。您可能感兴趣的 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)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

用法:

with Capturing() as output:
    do_something(my_object)
Run Code Online (Sandbox Code Playgroud)

3. 使用 redirect_stdout 捕获输出

import io
from contextlib import redirect_stdout

f = io.StringIO()
with redirect_stdout(f):
    do_something(my_object)
out = f.getvalue()
Run Code Online (Sandbox Code Playgroud)

4. 使用 %%capture 魔法命令捕获

捕捉魔法

分页输出

您可以使用 mag %page

%page -r <variablename>
Run Code Online (Sandbox Code Playgroud)

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

或者你可以使用 Ipython 代码

from IPython.core import page
page.page(variable)
Run Code Online (Sandbox Code Playgroud)

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

PS:一些有用的线程

如何从 Python 函数调用中捕获 stdout 输出?

如何在python中重定向函数的打印输出

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

重载打印蟒蛇