打包包含C共享库的Python库的最佳方法是什么?

时间:2014-06-05 14:26:13

标签: python c distutils

我编写了一个库,其主要功能是用C实现的(速度很关键),周围有一个很薄的Python层来处理ctypes肮脏。

我要打包它,我想知道我最好怎么做。它必须与之交互的代码是一个共享库。我有一个Makefile,它构建C代码并创建.so文件,但我不知道如何通过distutils编译它。我应该通过覆盖make命令与subprocess呼叫install(如果是,install是这个地方,或build更合适?)

更新:我想注意,这是不是 Python扩展。也就是说,C库不包含自己与Python运行时交互的代码。 Python正在对直接C共享库进行外部函数调用。

3 个答案:

答案 0 :(得分:2)

如果您按照有关如何create Python extensions in C的说明操作,则应该像this documentation一样登记扩展模块。
因此,您的库的setup.py脚本应如下所示:

from distutils.core import setup, Extension
setup(
   name='your_python_library',
   version='1.0',
   ext_modules=[Extension('your_c_extension', ['your_c_extension.c'])],
)

distutils知道如何编译扩展到C共享库以及放置它的位置。

当然我没有关于你的图书馆的更多信息,所以你可能想要为setup(...)电话添加更多的参数。

答案 1 :(得分:1)

我考虑将python模块构建为普通共享库构建的子项目。因此,使用automake,autoconf或类似的东西来构建共享库,有一个带有setup.py的python_bindings目录和你的python模块。

答案 2 :(得分:1)

我有类似的需求,发现这个答案有用:Python setup.py call makefile don't include binaries

我的发行版的src目录中有一个ANSI C库。在src目录中是一个Makefile,它在我的包目录(liblsd.so)中构建一个名为lsd的文件。我在setup.py中调用它,然后告诉setup使用package_data参数包含库文件。

import os.path
import subprocess

from setuptools import setup

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
    readme = f.read()

subprocess.call(['make', '-C', 'src'])

setup(name='LSD',
  version='0.0.1',
  description='Python bindings for the LSD line segment detector.',
  long_description=readme,
  author='Geoff Hing',
  author_email='geoffhing@gmail.com',
  url='https://github.com/ghing/python-lsd',
  packages=['lsd'],
  package_data={'lsd': ['liblsd.so']},
  include_package_data=True,
  classifiers=[
      'Development Status :: 1 - Planning',
      'Intended Audience :: Developers',
      'License :: OSI Approved :: MIT License',
      'Operating System :: OS Independent',
      'Programming Language :: Python',
      'Programming Language :: C',
      ],
 )
相关问题