为什么jupyter笔记本只打印一次cython结果? [英] Why jupyter notebook only prints the cython result once?
问题描述
我是cython的新手(现在仅用于一点操作)。
我使用以下代码在jupyter笔记本中查看它的一般概念。
I am new to cython(only use it for doing a little hw now). I use the following code to see a general idea of it in jupyter notebook.
%load_ext Cython
%%cython
def cfunc(int n):
cdef int a = 0
for i in range(n):
a += i
return a
print(cfunc(10))
但是,它仅打印出结果45一次。当我运行打印功能时,该单元格不会显示45个人。
However, it only prints out the result 45 once. When I run the print function, the cell doesn't show 45 anyone.
代码是否有问题?我怎样才能使单元格打印出与普通python代码相同的45格?谢谢。
Is there any problems with the code? How can I make the cell prints out 45 just the same as a normal python code? Thanks.
推荐答案
运行 %% cython
时,发生了很多魔术在引擎盖下。在详细模式下调用魔术时,可以看到部分内容,即 %% cython --verbose
:
When running %%cython
-magic a lot happens under the hood. One can see parts of it when calling the magic in verbose mode, i.e. %%cython --verbose
:
- 将生成一个名为
_cython_magic_b599dcf313706e8c6031a4a7058da2a2.pyx
的文件。b599dcf313706e8c6031a4a7058da2a2
是%% cython
单元格的sha1哈希值,例如,它需要重新加载%% cython
单元(请参阅此 SO-post ) - 此文件被cythonized并构建为c扩展名为
_cython_magic_b599dcf313706e8c6031a4a7058da2a2
。 - 此扩展名已导入-这是您的代码打印45的时刻,此模块中的所有内容都添加到了全局命名空间。
- A file called
_cython_magic_b599dcf313706e8c6031a4a7058da2a2.pyx
is generated.b599dcf313706e8c6031a4a7058da2a2
is the sha1-hash of the%%cython
-cell, which is needed for example to be able to reload a%%cython
-cell (see this SO-post). - This file is cythonized and build to a c-extension called
_cython_magic_b599dcf313706e8c6031a4a7058da2a2
. - This extension gets imported - this is the moment your code prints 45, and everything from this module is added to the global namespace.
何时如果再次执行该单元,则以上内容均不会发生:给定机器可以看到的哈希值,该单元已被执行并已加载-因此无所事事。仅当单元格的内容发生更改并因此更改其哈希值时,才会使用现金,而是执行上面的3个步骤。
When you execute the cell again, nothing of the above happens: given the sha-hash the machinery can see, that this cell was already executed and loaded - so nothing to be done. Only when the content of the cell is changed and thus its hash the cash will not be used but the 3 steps above executed.
要强制执行上述步骤,请执行以下步骤必须将-force
(或 -f
)选项传递给 %% cython
-magic-cell,即:
To enforce that the steps above are performed one has to pass --force
(or -f
) options to the %%cython
-magic-cell, i.e.:
%%cython --force
...
# 45 is printed
但是,因为重新构建扩展项已经很长时间了消费者可能更喜欢以下内容
However, because building extension anew is quite time consuming one would probably prefer the following
%%cython
def cfunc(int n):
cdef int a = 0
for i in range(n):
a += i
return a
# put the code of __main__ into a function
def cython_main():
print(cfunc(10))
# execute the old main
cython_main()
,现在在新单元格中调用 cython_main()
,因此它会像普通的python代码一样重新评估会。
and now calling cython_main()
in a new cell, so it gets reevaluated the same way the normal python code would.
这篇关于为什么jupyter笔记本只打印一次cython结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!