繁体   English   中英

在IPython中分页stdout输出

[英]Paging stdout output in 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 ...

我想翻阅function_that_prints_a_lotstdout输出。

另一个例子:

In [1]: %run script_that_prints_a_lot.py

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

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

捕捉魔法

分页输出

你可以使用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:一些有用的线程

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

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

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

重载打印python

使用来自各种来源的点点滴滴,但基本上来自IPython的食谱定义来自IPython官方文档的定制魔法

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()将无效...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM