如何在编译之前调试一个cython代码?
问题描述:
我最近遇到了sentdex tutorial for cython。在试用他的教程代码时,我注意到的是在编译之前我们将如何调试我们的cython代码。如何在编译之前调试一个cython代码?
我们可以通过在我们的解释器中运行example_original.py
来调试原始代码。
#example_original.py
def test(x):
y = 0
for i in range(x):
y += i
return y
print test(20)
但是cythonized代码dosent工作。这是我试图
1)PY文件
#example_cython.py
cpdef int test(int x):
cdef int y = 0
cdef int i
for i in range(x):
y += i
return y
print test(5)
错误
File "example_cython.py", line 3
cpdef int test(int x):
^
SyntaxError: invalid syntax
2)PYX文件
#example_cython.pyx
cpdef int test(int x):
cdef int y = 0
cdef int i
for i in range(x):
y += i
return y
print test(5)
错误
./example_cython: not found
的两种方式
在编译之前调试cython代码的正确方法是什么?
答
要检查您的Cython代码在语法上是否正确,并且没有可通过静态分析检测到的明显问题,可以使用cython
或cythonize
命令行工具。
cython path/to/file.pyx
运行Cython编译器,将Cython代码翻译成保存在同名文件中的C代码,其扩展名为.c
,而不是.pyx
。如果检测到问题,它们将被写入STDOUT/STDERR,但仍可能会生成.c
文件。
您可以将-a
选项传递给该程序,让编译器生成一个额外的HTML文件,该文件将突出显示部分代码,这会导致额外的Python开销。
这实际上并没有将你的代码编译成你可以用Python导入的共享库。您需要在生成的C代码上调用C编译器,通常通过Python的工具链setuptools
/distutils
。
我不认为这个问题有多大意义。 Cython是一种编译语言。要调试它,你必须编译它。 – DavidW