[英]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_lot
的stdout
輸出。
另一個例子:
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
捕獲輸出
輸出捕獲可以通過多種方式完成
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)
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)
import io
from contextlib import redirect_stdout
f = io.StringIO()
with redirect_stdout(f):
do_something(my_object)
out = f.getvalue()
分頁輸出
你可以使用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:一些有用的線程
https://github.com/ipython/ipython/wiki/Cookbook:-Sending-built-in-help-to-the-pager
使用來自各種來源的點點滴滴,但基本上來自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.