如何在编译之前调试cython代码?

时间:2017-10-06 15:10:25

标签: python cython cythonize

我最近遇到了sentdex tutorial for 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代码非常有用。这是我试过的两种方式

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代码的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

要检查您的Cython代码在语法上是否正确,并且静态分析无法检测到明显的问题,您可以使用cythoncythonize命令行工具。

cython path/to/file.pyx运行Cython编译器,将Cython代码转换为保存在文件中的C代码,该文件具有.c扩展名而不是.pyx的同名。如果检测到问题,它们将被写入STDOUT / STDERR,但仍可能生成.c文件。

您可以将-a选项传递给此程序,以使编译器生成一个额外的HTML文件,该文件将突出显示部分代码,从而产生额外的Python开销。

这实际上并没有将您的代码编译成可以使用Python导入的共享库。您需要在生成的C代码上调用C编译器,通常是通过Python的setuptools / distutils工具链。

相关问题