Cython primes example - SyntaxError: invalid syntax

Cython primes example - SyntaxError: invalid syntax

我正在 Linux 学习 Cython,并且正在使用 Cython 教程页面上的示例:

https://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html#primes

我正在研究素数的例子。其中有代码:

def primes(int nb_primes):
    cdef int n, i, len_p
    cdef int p[1000]
    if nb_primes > 1000:
        nb_primes = 1000

    len_p = 0  # The current number of elements in p.
    n = 2
    while len_p < nb_primes:
        # Is n prime?
        for i in p[:len_p]:
            if n % i == 0:
                break

        # If no break occurred in the loop, we have a prime.
        else:
            p[len_p] = n
            len_p += 1
        n += 1

    # Let's return the result in a python list:
    result_as_list  = [prime for prime in p[:len_p]]
    return result_as_list

我已将代码保存为 primes.pyx 和 运行 setup.py。

看起来像:

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("primes.pyx")
)

但是当我使用

导入素数时
>>> import primes

我收到错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vagrant/merlin/scoleman/test_cython/primes.py", line 1
    def primes(int nb_primes):

我有 primes.cprimes.pyx 个文件。为什么会出现此错误?

您错过了将其构建到 pyd 的步骤。

创建 setup.py :

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("primes.pyx"),
)

和运行 python setup.py build_ext --inplace在命令行中构建它。

这些在文档的上半部分。