Python 使用Cython创建扩展名,使用与源文件不同的名称
我知道如何使用Python 使用Cython创建扩展名,使用与源文件不同的名称,python,gcc,cython,Python,Gcc,Cython,我知道如何使用cythonize-omymodule.cmymodule.py或使用cython命令从Python生成C代码。生成的C文件必须使用gcc或任何其他C编译器编译为Python扩展,我也可以这样做。如果我希望它非常简单,我只需要使用distutils/setuptools和python setup.py build\u ext 但我不知道如何使扩展名文件(pyd/so)与源文件名不同。我不能简单地重命名该文件,因为扩展名中必须有一个函数PyInit\u modulename,并且我不
cythonize-omymodule.cmymodule.py
或使用cython
命令从Python生成C代码。生成的C文件必须使用gcc或任何其他C编译器编译为Python扩展,我也可以这样做。如果我希望它非常简单,我只需要使用distutils
/setuptools
和python setup.py build\u ext
但我不知道如何使扩展名文件(pyd/so)与源文件名不同。我不能简单地重命名该文件,因为扩展名中必须有一个函数PyInit\u modulename
,并且我不能将modulename.pyd
更改为\u modulename.pyd
,这将需要PyInit\u modulename
,并抛出此验证:
ImportError: dynamic module does not define init function (PyInit__modulename)
基本上应该是这样的:
mymodule.py -> _mymodule.pyd
例如,如果我有两个同名但结尾不同的文件(py/pyd/pyc/pyo/so/dll),这样可以避免导入混淆:
代码:
我需要的是:
mydir/
mymodule.py
_mymodule.pyd <- Note the underscore!
但我到底怎么能这样编译呢
提前谢谢你
我只有一个想法:我想我需要从cython的C代码生成开始。在你的
setup.py中试试这个
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np # if it requires numpy
ext_modules = [Extension("desired_name",["original_name.pyx"])]
setup(
name= 'Generic model class',
cmdclass = {'build_ext': build_ext},
include_dirs = [np.get_include()], # only if it requires numpy
ext_modules = ext_modules)
这不起作用,由于缺少PyInit_original_name函数,它会抛出一个导入错误。我以前已经试过了,太容易了!似乎影响模块名称的唯一方法是更改cython文件的名称,即\u modulename.pyx
@J.J.Hakala-是的,经过几天的研究,我已经想到了这一点。我为此编写了一个脚本,它会自动将temp dir中的文件保存为给定名称并编译文件
mydir/
mymodule.py
_mymodule.pyd <- Note the underscore!
import mymodule as script
script.func()
# Run the code from the python file
import _mymodule as extension
extension.func()
# Run code from the extension
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np # if it requires numpy
ext_modules = [Extension("desired_name",["original_name.pyx"])]
setup(
name= 'Generic model class',
cmdclass = {'build_ext': build_ext},
include_dirs = [np.get_include()], # only if it requires numpy
ext_modules = ext_modules)