为预构建的仅C扩展模块创建Python包 [英] Creating a Python package for a C extension-only module which is pre-built
问题描述
我想为一个项目创建一个程序包,该程序包不包含任何 .py
源文件,但已完全实现为Python C扩展(结果为 .so
)。另外,假设 .so
已经由一个单独的构建过程(例如CMake)构建。
I want to create a package for a project that does not contain any .py
source files, but is completely implemented as a Python C extension (resulting in an .so
). Additionally, assume that the .so
is already built by a separate build process (say CMake).
我知道setuptools / distutils至少需要一个目录结构:
I know that setuptools/distutils minimally requires a directory structure:
- mymodule
- __ init __。py
但是我真正想要的是
mymodule
由C扩展提供(例如mymodule.so
),以便在安装软件包后,import mymodule
与直接导入mymodule.so
具有相同的效果。But what I really want is for
mymodule
to be provided by a C extension (saymymodule.so
) such that after installing the package,import mymodule
has the same effect as directly importingmymodule.so
.我知道我可以使用这种目录结构:
I know that I could have this kind of directory structure:
- mymodule
- __init __。py
- mymodule_native.so
并具有
__ init __。py
为:from mymodule_native import *
这种作品,但对象
A
从mymodule
实际上看起来像mymodule.mymodule_native.A
。This kind of works, but an object
A
imported frommymodule
will actually look likemymodule.mymodule_native.A
.推荐答案
如果扩展是由setuptools配置的,则可能。
It's possible if the extension is configured by setuptools.
例如:
from setuptools import setup, Extension extension = Extension('mymodule', sources=[<..>]) setup('mymodule', ext_modules=[extension])
安装后,扩展名可以作为
import mymodule
使用。请注意,未使用find_packages
。Once installed, the extension is available as
import mymodule
. Note thatfind_packages
is not used.此操作必须由setuptools完成,否则将需要<$如果未提供
ext_modules
,则设置c $ c> packages 。This needs to be done by setuptools as it would otherwise require a
packages
setting if noext_modules
are provided.但是,这使得
.so
模块直接安装在site-packages
目录下,并且会与任何同名的非扩展python模块。However, this makes the
.so
module be installed directly undersite-packages
directory and will conflict with any non-extension python modules of the same name.这通常被认为是不好的做法,大多数库使用带有单个
__ init__的裸python模块。 .py
,可以在其中使用扩展名。This is generally considered bad practice and most libraries use a bare python module with a single
__init__.py
, under which the extension is available.您将来可能会在模块中添加python代码,并希望将纯扩展代码中的python代码。或者,您可能想要添加多个扩展名,而这种扩展名是无法通过这种方式实现的,至少在保持相同的程序包名称的情况下是不可能的。
You may in future add python code to your module for example and wish to separate the pure python code from extension code. Or you may want to add more than one extension which is not possible in this way, at least not while keeping the same package name.
因此,<$ c这样的结构$ c> mymodule。< python modules> 和
mymodule.my_extension
是有意义的。So a structure like
mymodule.<python modules>
andmymodule.my_extension
makes sense.我个人会为扩展代码和python代码分别命名,而 not 从< ext mod> ;在
__ init __。py
中导入* 。Personally I'd have separate name spaces for extension code vs python code and not do
from <ext mod> import *
in__init__.py
.这篇关于为预构建的仅C扩展模块创建Python包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!