Problem
大多数 iPython“神奇函数”对我来说立刻就可以正常工作:%hist
, %time
, %prun
等等。但是,我注意到%lprun
无法使用 iPython 找到它,因为我最初安装了它。
尝试解决
然后我发现我应该安装line_profiler
模块。我已经安装了这个模块,但似乎仍然无法让魔法功能正常工作。如果我尝试打电话%lprun
,iPython仍然找不到该函数。如果我用全名来称呼它(line_profiler.magic_lprun
),可以找到该函数,但我根本无法让它工作。下面是我所做的一个示例(这是从“Python for Data Analysis”书中逐步获取的):
成功使用%prun
[In:]
def add_and_sum(x, y):
added = x + y
summed = added.sum(axis=1)
return summed
x = randn(3000, 3000)
y = randn(3000, 3000)
add_and_sum(x, y)
正如预期的那样,我得到了一个很好的答案:
[Out:]
array([-23.6223074 , -10.08590736, -31.2957222 , ..., -14.17271747,
63.84057725, -50.28469621])
我可以执行分析魔法功能%prun
:
[In:]
%prun add_and_sum(x, y)
[Out:]
6 function calls in 0.042 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.020 0.020 0.029 0.029 <ipython-input-27-19f64f63ba0a>:1(add_and_sum)
1 0.013 0.013 0.042 0.042 <string>:1(<module>)
1 0.009 0.009 0.009 0.009 {method 'reduce' of 'numpy.ufunc' objects}
1 0.000 0.000 0.009 0.009 _methods.py:16(_sum)
1 0.000 0.000 0.009 0.009 {method 'sum' of 'numpy.ndarray' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
使用失败%lprun
但当我尝试时%lprun
,我什么也得不到:
[In:]
%lprun -f add_and_sum add_and_sum(x, y)
[Out:]
ERROR: Line magic function `%lprun` not found.
如果我尝试使用其标准名称调用该函数,它也不起作用:
[In:]
line_profiler.magic_lprun -f add_and_sum.test test.add_and_sum(x, y)
[Out:]
line_profiler.magic_lprun -f add_and_sum.test test.add_and_sum(x, y)
^
SyntaxError: invalid syntax
但该库已正确导入,或者至少是这样的:
[In:]
line_profiler
[Out:]
<module 'line_profiler' from '/Users/<edit>/anaconda/lib/python2.7/site-packages/line_profiler-1.0b3-py2.7-macosx-10.5-x86_64.egg/line_profiler.pyc'>
[In:]
line_profiler.magic_lprun
[Out:]
<function line_profiler.magic_lprun>
似乎我应该配置一些额外的东西,以便我添加的这些新的神奇功能可以被识别。我通过网络搜索找不到任何东西。
我将 Spyder 作为 IDE 运行(仍然使用 iPython 作为控制台),但我也直接使用 iPython 和 iPython Notebook 进行了尝试。我在任何形式上都没有运气。