python文件打包/導入 .so 文件


打包so文件

 

准備工作

  環境是可為linux/centos,我Windows10本地是Bash on Ubuntu on Windows,用起來很方便,命令行打bash即進入命令行

  思路是先將py轉換為c代碼,然后編譯c為so文件

  所以要安裝以下內容

    python 安裝:cython

      pip install cython

    linux 安裝:python-devel,gcc

      yum install python-devel

      yum install gcc

 

初步編譯

  在testing文件夾下有your_file.py文件待編譯,內容如下

#-* -coding: UTF-8 -* -
__author__ = 'Arvin' class test: def say(self): print 'hello'

  新建setup.py,內容如下

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules = cythonize(["your_file.py"]))

  在bash中執行

cd testing
python setup.py build_ext

 

  運行后會生成build文件夾,如下,lib.linux-x86_64-2.7下就是我們想要的.so文件

  

  現在so文件就可以像普通py文件一樣導入了

cd build/lib.linux-x86_64-2.7/
python
from your_file import test
test().say()

 

集成編譯

  最新代碼github:https://github.com/ArvinMei/py2so.git

  做了以下內容:

    1.文件夾編譯

    2.刪除編譯出的.c文件

    3.刪除編譯的temp文件夾

#-* -coding: UTF-8 -* -
__author__ = 'Arvin'

import sys, os, shutil, time
from distutils.core import setup
from Cython.Build import cythonize

starttime = time.time()
currdir = os.path.abspath('.')
parentpath = sys.argv[1] if len(sys.argv)>1 else ""
setupfile= os.path.join(os.path.abspath('.'), __file__)
build_dir = "build"
build_tmp_dir = build_dir + "/temp"

def getpy(basepath=os.path.abspath('.'), parentpath='', name='', excepts=(), copyOther=False,delC=False):
    """
    獲取py文件的路徑
    :param basepath: 根路徑
    :param parentpath: 父路徑
    :param name: 文件/夾
    :param excepts: 排除文件
    :param copy: 是否copy其他文件
    :return: py文件的迭代器
    """
    fullpath = os.path.join(basepath, parentpath, name)
    for fname in os.listdir(fullpath):
        ffile = os.path.join(fullpath, fname)
        #print basepath, parentpath, name,file
        if os.path.isdir(ffile) and fname != build_dir and not fname.startswith('.'):
            for f in getpy(basepath, os.path.join(parentpath, name), fname, excepts, copyOther, delC):
                yield f
        elif os.path.isfile(ffile):
            ext = os.path.splitext(fname)[1]
            if ext == ".c":
                if delC and os.stat(ffile).st_mtime > starttime:
                    os.remove(ffile)
            elif ffile not in excepts and os.path.splitext(fname)[1] not in('.pyc', '.pyx'):
                if os.path.splitext(fname)[1] in('.py', '.pyx') and not fname.startswith('__'):
                    yield os.path.join(parentpath, name, fname)
                elif copyOther:
                        dstdir = os.path.join(basepath, build_dir, parentpath, name)
                        if not os.path.isdir(dstdir): os.makedirs(dstdir)
                        shutil.copyfile(ffile, os.path.join(dstdir, fname))
        else:
            pass

#獲取py列表
module_list = list(getpy(basepath=currdir,parentpath=parentpath, excepts=(setupfile)))
try:
    setup(ext_modules = cythonize(module_list),script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
except Exception, ex:
    print "error! ", ex.message
else:
    module_list = list(getpy(basepath=currdir, parentpath=parentpath, excepts=(setupfile), copyOther=True))

module_list = list(getpy(basepath=currdir, parentpath=parentpath, excepts=(setupfile), delC=True))
if os.path.exists(build_tmp_dir): shutil.rmtree(build_tmp_dir)

print "complate! time:", time.time()-starttime, 's'

 

注意問題

  1.編譯后執行需要相同的python版本和編碼

  2.py中使用__file__內置變量的文件編譯后調用時會出問題,暫時沒有解決,還需要使用pyc代替

  3.使用時注意權限控制

 

導入so文件

import sys
sys.path.append(r'/home/project/python_project/utils')  # 參數為存放so文件的文件夾路徑

from functions import function # functions為utils文件夾下so文件 function為functions文件中的方法
do soemthing
......


免責聲明!

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



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