python - 在 PyCharm 中使用 Cython - 如何运行已编译的文件
问题描述
我正在尝试找出如何使用 Cython 并面临一些问题。我使用 python 3.6 和 PyCharm Professional 作为 IDE。当前环境是 OSX。
首先,我尝试创建一个包含两个文件的简单应用程序:common.pyx:
cpdef cppfun(t):
s = 0
for i in range(t):
for j in range(t):
s = s + i*j
return s
def pyfun(t):
s = 0
for i in range(t):
for j in range(t):
s = s + i*j
return s
和我试图在 PyCharm 中运行的主文件。据我了解,有必要将我的 common.pyx 编译为“.so”文件。为此,我创建了 setup.py 具有以下内容的文件:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("cmn", ["common.pyx"],
libraries=["m"], extra_compile_args=["-ffast-math"])
]
setup(
name="cmn",
cmdclass={"build_ext": build_ext},
ext_modules=ext_modules
)
并在终端中运行此命令:
python setup.py build_ext --inplace
因此,我试图将编译后的文件导入到我的 runner.py:
import time
from ctypes import cdll
cmn = cdll.LoadLibrary('../cmn.cpython-36m-darwin.so')
if __name__ == '__main__':
count = 100000
start_time = time.time()
cmn.pyfun(count)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
cmn.cppfun(count)
print("--- %s seconds ---" % (time.time() - start_time))
但出现错误:
文件“/path-to-env/lib/python3.6/ctypes/init .py ”,第 366 行,在 getitem func = self._FuncPtr((name_or_ordinal, self)) AttributeError: dlsym(0x7fb77cd02120, pyfun): symbol not成立
最终,我不知道如何使它工作。我有一个想法,我必须使用:
from common import pyfun, cppfun
import pyximport; pyximport.install()
并避免通过终端手动编译,但在这种情况下,我会收到以下错误:
ModuleNotFoundError:没有名为“common”的模块
解决方案
推荐阅读
- node.js - Vue.js 图像纵横比
- node.js - node.js 可以将文件/文件夹发送到回收站(MacOS 上的垃圾箱)而不是 fs.unlink / fs.rmdir 吗?
- r - 如何从 R 快速连接(访问)IBM 云对象存储?
- netsuite - SuiteScript 2 file.File 参数类型错误
- luxon - 如何在 luxon 中创建 momentLocaleData.firstDayOfWeek()?
- jquery - jQuery 错误 MaterializeCSS
- javascript - 大数据网格单元的实时更新:方法
- reactjs - 如何使用 Material UI 动态创建选择和状态?
- oracle - Oracle 12c - 从视图中获取 IMPORT_TABLE_STATS
- networking - Kubernetes 间歇性网络故障,anonymous-auth=false