【发布时间】:2017-06-27 17:58:17
【问题描述】:
我正在学习如何使用 Cython 高效地编译 Python 代码并使其更快。
这是我到目前为止所做的:
- 我创建了一个名为
math_code_python.py的 Python 文件,并在其中放入了 4 个简单的函数。 - 我将该文件保存为
math_code_cython.pyx。 - 我创建了一个名为
setup.py的设置文件。 - 我在
Command Prompt中输入了python C:\Users\loic\Documents\math_code\setup.py build_ext --inplace。 - 我得到了一个名为
math_code_cython.cp36-win_amd64.pyd的编译文件,我将其重命名为math_code_pyd.pyd。 -
最后,我创建了一个名为
test_math_code.pyd的Python 文件,其中只有import math_code_pyd。当我执行这个文件时,我收到了这条消息:ImportError: dynamic module does not define module export function
我做了一些研究,感谢这些帖子,我明白我必须提供init function:
- https://bytes.com/topic/python/answers/694888-constructor-initialization-function-module
- Python 3.5 ImportError: dynamic module does not define module export function (PyInit_cv2)
我的问题是:我该怎么做?我是否必须在math_code_python.py 的末尾添加一个函数,如下所示?
def __init__(self):
# something ?
我的 Python 版本:
Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]
math_code_python.py
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
def fibo(n):
if n==0 or n==1:
return 1
else:
return fibo(n-1)+fibo(n-2)
def dicho(f, a, b, eps):
assert f(a)*f(b) < 0
while b-a > eps:
M = (a+b)/2.
if f(a) * f(M) > 0:
a = M
else:
b = M
return M
def newton(f, fp, x0, eps):
u = x0
v = u - f(u)/fp(u)
while abs(v-u) > eps:
u = v
v = u - f(u)/fp(u)
return v
setup.py
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from Cython.Distutils import build_ext
from Cython.Build import cythonize
import numpy as np
setup(name = "maido",
include_dirs = [np.get_include()],
cmdclass = {'build_ext': build_ext},
ext_modules = cythonize(r"C:\Users\loic\Documents\math_code\math_code_cython.pyx"),
)
【问题讨论】: