cython编译Python为c语⾔
第⼀种办法:
执⾏命令:cython test.py
结果:会在同⼀⽬录下⾯⽣成test.c⽂件
执⾏命令: gcc -c -fPIC -I /usr/include/python2.7 test.c
结果:在同⼀⽬录下⾯⽣成test.o⽂件
执⾏命令: gcc -shared test.o -c test.so
结果:在同⼀⽬录下⾯⽣成test.so⽂件
最后,⽣成的test.so⽂件就是需要的⽂件
第⼆种办法:
[setup.py]
import setup
from Cython.Build import cythonize
setup(
name = "test",
ext_modules = cythonize("test.py")
)
执⾏命令: python setup.py build_ext --inplace
第⼆种办法是对单独⽂件进⾏编译,下⾯介绍⼀种批量的办法:
#-*- coding:utf-8 -*-_
import os
import re
import Extension, setup
from Cython.Build import cythonize
from Cython.Compiler import Options
# __file__ 含有魔术变量的应当排除,Cython虽有个编译参数,但只能设置静态。
exclude_so = ['__init__.py', 'run.py']
sources = 'backend'
extensions = []
remove_files = []
for source,dirnames,files in os.walk(sources):
for dirpath, foldernames, filenames in os.walk(source):
if 'test' in dirpath:
break;
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"],编程先学c语言还是python
extra_link_args = ["-Wl,--strip-all"]))
remove_files.append(file_path[:-3]+'.py')
remove_files.append(file_path[:-3]+'.pyc')
Options.docstrings = False
compiler_directives = {'optimize.unpack_method_calls': False, 'always_allow_keywords': True}
setup(
# cythonize的exclude全路径匹配,不灵活,不如在上⼀步排除。
ext_modules = cythonize(extensions, exclude = None, nthreads = 20, quiet = True, build_dir = './build',
language_level = 2, compiler_directives = compiler_directives))
# 删除py和pyc⽂件
for remove_file in remove_files:
if ists(remove_file):
执⾏命令: python setup.py build_ext --inplace
结果:最后⽣成.so⽂件,删除中间结果。
重点提⼀下,在编译flask代码时,遇到问题,报错:参数不够(⼤体意思是这样,错误未截图),在compiler_directives中添加:{always_allow_keywords:True}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论