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]
from distutils.core 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 
from distutils.core 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"],
                                  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 os.path.exists(remove_file):
        os.remove(remove_file)
  • 執行命令: python setup.py build_ext --inplace
  • 結果:最后生成.so文件,刪除中間結果。

重點提一下,在編譯flask代碼時,遇到問題,報錯:參數不夠(大體意思是這樣,錯誤未截圖),在compiler_directives中添加: {always_allow_keywords:True}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM