打包Python程序为so文件及其调用方法

参考资料:https://blog.csdn.net/qq_16912257/article/details/80161112
     https://blog.csdn.net/linshenyuan1213/article/details/72677246
1.编写setput.py文件:
    setup.py文件内容如下:

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

extensions = [
    Extension("UIBox", ["UIBox.py"],
              include_dirs=["../include"],
              libraries=["../lib/cv2/cv2.cpython-36m-aarch64-linux-gnu.so",
                         "../lib/dlib-19.17.0-py3.6-linux-aarch64.egg/dlib.cpython-36m-aarch64-linux-gnu.so"],
              library_dirs=["../lib/cv2",
                            "../lib/dlib-19.17.0-py3.6-linux-aarch64.egg"]),

    Extension("UIShow", ["UIShow.py"],
              include_dirs=["../include"],
              libraries=["../lib/cv2/cv2.cpython-36m-aarch64-linux-gnu.so",
                         "../lib/dlib-19.17.0-py3.6-linux-aarch64.egg/dlib.cpython-36m-aarch64-linux-gnu.so"],
              library_dirs=["../lib/cv2",
                            "../lib/dlib-19.17.0-py3.6-linux-aarch64.egg"]),
    ……
]

setup(ext_modules=cythonize(extensions))

    整个工程中包括多少个py文件,就写多少个Extension,并把需要调用的其他库路径在include_dirs、libraries、library_dirs中进行设置。
2.编译so文件,执行以下命令:

    python setup.py build_ext
3.调用so文件
    在调用的py文件中加入以下内容即可
    import sys
    sys.path.append('../lib.linux-aarch64-3.6') #加载so文件(入参为so文件路径)
    from libSupernode import libSupernode #import so文件中的相关类

你可能感兴趣的:(python)