【发布时间】:2020-02-24 10:19:19
【问题描述】:
我是 Cython 的新手,只是想尝试一个简单的脚本。我无法从模块中导入函数并在另一个文件中使用它,但如果我在同一个文件中声明该函数,它就可以正常工作。这里可能是什么问题。我错过了什么吗?
这是sn-p的原始代码(test_cy.pyx):
# test_cy.pyx
import json
cpdef char* say_hello():
message = json.dumps({"message": "Hello world"})
return message.encode()
cdef char* fn(int n):
cdef char* hello = say_hello()
return hello
def test():
cdef char* n = fn(1000)
print(n)
我可以运行它(编译后):
>>> import test_cy
>>> test_cy.test()
b'Hello world'
但是,如果我将 say_hello 函数移动到另一个文件 (utils.pyx):
# utils.pyx
import json
cpdef char* say_hello():
message = json.dumps({"message": "Hello world"})
return message.encode()
... 并将其导入到我原来的 test_cy.pyx 文件中,如下所示:
# test_cy.pyx
from utils import say_hello
cdef char* fn(int n):
cdef char* hello = say_hello()
return hello
def test():
cdef char* n = fn(1000)
print(n)
我无法编译它,因为我收到以下错误:
>>> python3 setup.py build_ext --inplace
...
Error compiling Cython file:
------------------------------------------------------------
...
from utils import say_hello
cdef char* fn(int n):
cdef char* hello = say_hello()
^
------------------------------------------------------------
test_cy.pyx:4:7: Storing unsafe C derivative of temporary Python reference
Traceback (most recent call last):
File "setup.py", line 11, in <module>
sources=["utils.pyx"]
File "/Users/asim/.pyenv/versions/3.6.9/lib/python3.6/site-packages/Cython/Build/Dependencies.py", line 1101, in cythonize
cythonize_one(*args)
File "/Users/asim/.pyenv/versions/3.6.9/lib/python3.6/site-packages/Cython/Build/Dependencies.py", line 1224, in cythonize_one
raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: test_cy.pyx
这是我的 setup.py 文件:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
ext_modules = cythonize([
Extension("test_cy",
sources=["test_cy.pyx"]
),
Extension("utils",
sources=["utils.pyx"]
)
])
)
请帮助我,像从另一个模块导入函数这样简单的事情不应该这么复杂。我可能会遗漏一些微不足道的东西。谢谢!
【问题讨论】: