在IPython中分页标准输出 [英] Paging stdout output in IPython
问题描述
是否可以在(交互式)IPython会话中通过寻呼机传递 stdout
输出,例如 less
?如果是这样,怎么样?
例如,在
在[1]中:来自some_module import function_that_prints_a_lot
在[2]中:function_that_prints_a_lot()
...所有内容都滚动...
我想翻页 stdout
输出 function_that_prints_a_lot
。
另一个例子:
在[1]中:%运行script_that_prints_a_lot.py
我查看了IPython
分页输出
您可以使用magin %page
%page -r< variablename>
https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-page
或者你可以从IPython.core导入页面使用Ipython代码
page.page (变量)
有关详细信息,请参阅以下内容
PS:一些有用的主题
https://github.co m / ipython / ipython / wiki / Cookbook:-sending-built-in-help-to-the pager
Is it possible in an (interactive) IPython session to pass the stdout
output through a pager, like less
? If so, how?
For example, in
In [1]: from some_module import function_that_prints_a_lot
In [2]: function_that_prints_a_lot()
... everything scrolls away ...
I would like to page through the stdout
output of function_that_prints_a_lot
.
Another example:
In [1]: %run script_that_prints_a_lot.py
I've looked through IPython magic commands but didn't find any solution.
As discussed in chat there is no simple way of doing this. Since the function prints the values, the only thing you can do is Capture output + Then page output. There are few issues on jupyter that you might be interested in
https://github.com/jupyter/notebook/issues/2049
https://github.com/ipython/ipython/issues/6516
Capturing output
Output capturing can be done multiple ways
1. Overload Print Method
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. Capture output using 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
Usage:
with Capturing() as output:
do_something(my_object)
3. Capture output using 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 using %%capture magic command
Paging Output
You can use magin %page
%page -r <variablename>
https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-page
Or you can use Ipython code
from IPython.core import page
page.page(variable)
For more details refer to below
PS: Some helpful threads
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
这篇关于在IPython中分页标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!