Cython NameError:未定义名称"blah".Jupyter中的Cython魔术无法正常工作? [英] Cython NameError: name ' blah ' is not defined. Cython magic in Jupyter not working properly?

查看:56
本文介绍了Cython NameError:未定义名称"blah".Jupyter中的Cython魔术无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用cython在Jupyter中更快地运行某些代码,但是由于某些原因,在%% cython单元运行后,它无法记住"函数.我在网上找到的任何其他示例似乎都不是问题(例如:

I am trying to make some code run faster in Jupyter using cython but for some reason it doesn't "remember" functions after the %%cython cell has been run. This doesn't seem to be a problem with any other examples I have found online ( For instance : https://jakevdp.github.io/blog/2017/12/11/live-coding-cython-ising-model/ ). I am using Cython 0.29.15 and python 3.7.3.

示例:

%load_ext cython

%%cython

def function(x):
    y = 2*x
    return y

function(1)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-d7befaefa369> in <module>
----> 1 function(1)

NameError: name 'function' is not defined

我尝试了 cpdef cdef ,但是它们提供了相同的错误输出.

I have tried cpdef and cdef but those provide the same error output.

另一个例子:

%%cython 

cpdef int a = 0
for i in range(10):
    a += i

print(a)

什么都没打印

下一个单元格:

print(a)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-bca0e2660b9f> in <module>
----> 1 print(a)

NameError: name 'a' is not defined

推荐答案

我可以使用它.

%load_ext cython

%%cython

def function(x):
    y = 2*x
    return y

function(1)

2

可能存在一些安装问题.我不确定,我是新手,但是

There was some installation problem maybe. I am not sure, I'm a novice at this stuff but

.尝试重新安装cython-无效.

.Tried reinstalling cython-- didn't work.

.尝试重新安装anaconda3--无效.

.Tried reinstalling anaconda3-- didn't work.

.注意到我的终端正在使用python2,然后将其切换为python3( https://dev.to/irfnhm/how-to-set-python3-as-a-default-python-version-on-mac-4jjf )

.Noticed that my terminal was using python2 then switched that to python3 (https://dev.to/irfnhm/how-to-set-python3-as-a-default-python-version-on-mac-4jjf)

.然后重新安装了anaconda3(

.Then reinstalled anaconda3 (https://towardsdatascience.com/how-to-successfully-install-anaconda-on-a-mac-and-actually-get-it-to-work-53ce18025f97)

我不知道为什么这行得通(还是新手),但希望这对以后的人有所帮助.

I have no idea why this worked (again, novice) but hope this helps someone in the future possibly.

这篇关于Cython NameError:未定义名称"blah".Jupyter中的Cython魔术无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆