向Python扩展添加输出文件

2024-10-04 11:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了一个自定义的build_ext来构建一个有趣的扩展,我试图使pip友好。以下是我正在做的事情的精简版。在

foo_ext = Extension(
  name='foo/_foo',
  sources=foo_sources,
)

class MyBuildExt(build_ext):
  def build_extension(self, ext):
    # This standalone script builds the __init__.py file 
    #  and some .h files for the extension
    check_call(['python', 'build_init_file.py'])

    # Now that we've created all the init and .h code
    #  build the C/C++ extension using setuptools/distutils
    build_ext.build_extension(self, ext)

    # Include the generated __init__.py in the build directory 
    #  which is something like `build/lib.linux-x86/foo/`.  
    #  How can I get setuptools/distutils to install the 
    #  generated file automatically?!
    generated_file = 'Source/foo/__init__.py'
    output_path = '/'.join(self.get_outputs()[0].split('/')[:-1])
    self.move_file(generated_file, output_path)

setup(
    ...,
    ext_modules = [foo_ext],
    cmdclass={'build_ext' : MyBuildExt},
)

在打包这个模块并用pip安装之后,我在virtualenv的site packages目录中有一个模块foo。目录结构如下所示。在

^{pr2}$

egg-info/SOURCES.txt文件不包括我手动创建/移动的__init__.py文件。当我执行pip uninstall foo时,该命令将foo/__init__.py留在virtualenv的站点包中。我想让皮普删除整个包。如何将生成的__init__.py文件手动移到构建目录中,添加到已安装的输出文件列表中?在

我知道这是令人厌恶的和老套的,所以我欢迎恶心和粗糙的答案!在

尝试次数:

  1. 添加了packages=['foo']——当我这样做时,pip不构建扩展。还尝试调整包名的文件路径/命名空间版本——没有区别。在

Tags: pip文件thepybuildself目录foo
2条回答

为了让distutils安装一个Python包,您需要传递packages=['foo'],如果您要将它放在不是项目根级别的地方(我是指设置.py脚本),就像您在这里所做的一样,您还必须传递package_dir={'foo': 'Source'}或使用更简单的布局。如果你设置.py脚本包含这个packages参数,然后build命令将调用build_py命令将Python源文件(和目录)移动到build目录中,稍后install命令将复制该目录。在

这里的问题是您的foo/__init__.py文件是由build_ext命令生成的,该命令在build\py之后运行。您需要使用自定义生成命令覆盖该命令:

class MyBuild(build):
  sub_commands = [('build_clib', build.has_c_libraries),
                  ('build_ext', build.has_ext_modules),
                  ('build_py', build.has_pure_modules),
                  ('build_scripts', build.has_scripts),
                 ]

setup(..., cmdclass={'build': MyBuild, 'build_ext': MyBuildExt})

sub_commands属性中的元素是(command name,要调用的函数以决定是否运行命令)的元组;这在源代码中有记录,但我不记得文档中是否解释过。在标准的构建类中,build-py位于build-chu-clib之前。在python2.7的下一个版本中,我可能会改变这一点,因为据报道,它与2to3转换的交互非常糟糕。在

首先,扩展实例中的name参数应该是模块名(foo.\u foo),而不是路径。在

你试过把packages=['foo']添加到你的安装调用中了吗?在

相关问题 更多 >