是否可以在(交互式)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 魔术命令,但没有找到任何解决方案.
正如聊天中所讨论的那样,没有简单的方法可以做到这一点。由于该函数打印值,因此您唯一可以做的就是捕获输出 + 然后页面输出。您可能感兴趣的 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)
Run Code Online (Sandbox Code Playgroud)
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)
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)
分页输出
您可以使用 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:一些有用的线程
https://github.com/ipython/ipython/wiki/Cookbook:-Sending-built-in-help-to-the-pager
| 归档时间: |
|
| 查看次数: |
1101 次 |
| 最近记录: |