Cython primes 示例 - SyntaxError: invalid syntax.

问题描述 投票:-1回答:1

我正在Linux下学习Cython,正在通过Cython教程页面上的例子进行学习。

https:/cython.readthedocs.ioenlatestsrctutorialcython_tutorial.html#primes。

我正在研究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")
)

但是当我用primes导入primes时

>>> 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 文件。为什么会出现这个错误?

python cython
1个回答
1
投票

你错过了一个步骤,要把它建立成 pyd.

创建一个 setup.py :

from setuptools import setup
from Cython.Build import cythonize

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

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

这些都在你的文档的上半部分。

© www.soinside.com 2019 - 2024. All rights reserved.