分发带有已编译动态共享库的 Python 包

2022-01-13 00:00:00 python setuptools package distutils

问题描述

如何将 Python 模块与预编译的 .so 库打包在一起?具体来说,我该如何编写 setup.py 以便当我在 Python 中执行此操作时

How do I package a Python module together with a precompiled .so library? Specifically, how do I write setup.py so that when I do this in Python

>>> import top_secret_wrapper

不用设置LD_LIBRARY_PATH也能轻松找到top_secret.so?

It can easily find top_secret.so without having to set LD_LIBRARY_PATH?

在我的模块开发环境中,我的文件结构如下:

In my module development environment, I have the following file structure:

.
├── top_secret_wrapper
│   ├── top_secret.so
│   └── __init__.py
└── setup.py

__init__.py 里面,我有类似的东西:

Inside __init__.py, I have something like:

import top_secret

这是我的 setup.py

from setuptools import setup, Extension

setup(
    name = 'top_secret_wrapper',
    version = '0.1',
    description = 'A Python wrapper for a top secret algorithm',
    url = None,
    author = 'James Bond',
    author_email = 'James.Bond.007@mi6.org',
    license = 'Spy Game License',
    zip_safe = True,
)

我确定我的 setup.py 缺少指定 top_secret.so 位置的设置,但我不确定如何执行此操作.

I'm sure my setup.py is lacking a setting where I specify the location of top_secret.so, though I'm not sure how to do that.


解决方案

我最终做的是:

setup(
    name='py_my_lib',
    version=version,  # specified elsewhere
    packages=[''],
    package_dir={'': '.'},
    package_data={'': ['py_my_lib.so']},
)

这样我可以按名称导入库,并且没有其他级别的嵌套:

This way I get to import the lib by its name, and don't have another level of nestedness:

import py_my_lib

而不是

from py_my_lib_wrapper import py_my_lib

相关文章