捕获IPython魔术函数的结果 [英] Capture the result of an IPython magic function
问题描述
我正在尝试捕获IPython Notebook魔术函数的结果对象。具体来说,%timeit
I'm trying to capture the resulting object of IPython Notebook magic function. Specifically %timeit
所以下面的代码......
So the following code...
import time
def say_hello(n):
time.sleep(n)
print "hello"
t = %timeit say_hello(5)
打印到stdout:
1 loops, best of 3: 5 s per loop
但是,我想在变量 t
%timeit say_hello(5)的结果>。
However, I'd like to capture the result of %timeit say_hello(5)
in the variable t
.
一个名为 TimeitResult
由%timeit
生成,但我无法弄清楚如何从笔记本电脑中访问它。
A resulting object called TimeitResult
is generated by %timeit
, but I can't figure out how to access it from within a Notebook.
我想要一个更清洁的解决方案而不是使用 sys.stdout $ c手动捕获标准输出$ c>技巧(这段代码将成为演示文稿的一部分,所以我试图将其保持为直截了当可能)。任何人都有任何想法?
I'd like a cleaner solution than having to manually capture stdout using sys.stdout
tricks (this code will be part of a presentation so I'm trying to keep it as straight forward as possible). Anyone have any ideas?
推荐答案
在您链接的源文件中,docstring显示运行timeit magic函数的选项;其中一个是返回一个对象结果:
In the source file you linked to, the docstring shows the options for running the timeit magic function; one of which is returning an object result:
-o: return a TimeitResult that can be stored in a variable to inspect
the result in more details.
所以,如果你运行
obj = %timeit -o somefunc()
obj
将引用返回的结果对象(提示:在对象上使用tab完成,它将显示它具有的属性)。
obj
will reference the result object that was returned (hint: use tab completion on the object, that will show you the attributes it has).
这篇关于捕获IPython魔术函数的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!