这篇文章将为大家详细讲解有关Cython编译python为so的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
1. 编译出来的so比网上流传的其他方法小很多。
2. language_level 是python的主版本号,如果python版本是2.x,目前的版本Cython需要人工指定language_level.
3. python setup.py build_ext --inplace 执行脚本
4. 以下是代码片段
from distutils.core import Extension, setup
from Cython.Build import cythonize
from Cython.Compiler import Options
# __file__ 含有魔术变量的应当排除,Cython虽有个编译参数,但只能设置静态。
exclude_so = ['__init__.py', "mixins.py"]
sources = ['core', 'libs']
extensions = []
for source in sources:
for dirpath, foldernames, filenames in os.walk(source):
for filename in filter(lambda x: re.match(r'.*[.]py$', x), filenames):
file_path = os.path.join(dirpath, filename)
if filename not in exclude_so:
extensions.append(
Extension(file_path[:-3].replace('/', '.'), [file_path], extra_compile_args = ["-Os", "-g0"],
extra_link_args = ["-Wl,--strip-all"]))
Options.docstrings = False
compiler_directives = {'optimize.unpack_method_calls': False}
setup(
# cythonize的exclude全路径匹配,不灵活,不如在上一步排除。
ext_modules = cythonize(extensions, exclude = None, nthreads = 20, quiet = True, build_dir = './build',
language_level = 2 或者3 , compiler_directives = compiler_directives))
关于“Cython编译python为so的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。