Python 具有 C 扩展的项目 - 结构、导入和测试

Python project with C extensions - structure, imports and tests

用 python 编写的项目,带有一些 C 扩展(不使用 SWIG 等)。我正在尝试弄清楚如何构建我的项目,以便:

  1. 导入工作。导入共享对象
  2. 我不需要更改 PYTHONPATH(尝试弄清楚但失败了)。
  3. 以后分发项目包最简单

当前结构如建议的那样here:

Project\

    docs\  # mainly documentation, right?

    bin\   # empty

    setup.py # setup for the project, as suggested in the above link

    project\   
        __init__.py
        module.py

        tests\
             bla_test.py

    C\ # the package of C files
        file.c
        file.so
        other_c_stuff.c
        header.h
        setup.py # setup to compile the C files and create .so files
        build\ # contaisn a bunch of (hopefully) irrelevant stuf

它在 PyDev 中有效,但在 shell 中无效。理想的答案将解决以下问题:

  1. 建议的项目结构。
  2. 如何执行导入(例如,从 tests 中的模块)。
  3. 我应该(可以)将所有 C 文件保存在单独的库中吗?
  4. C 文件的构建是在哪个 setup.py 文件中完成的(我应该 post 它们在这里吗?)
  5. 是否可以在需要时自动构建?怎么样?

我试过了 relative imports - 由于某些原因,它们对我不起作用。 我看到 this question. He says - do whatever. But I can't get the imports to work. I read this answer, but have no clue what's all the stuff he has (and I don't have). The accepted answer doesn't help me because, again, the imports fail. This 博客接受的答案 posts 给出了很好的建议,但是,再次,进口!

我不想详细说明一般性答案,因为您已经链接到好的答案。

一些适合您的结构可能如下所示:

Project\

    build\ # directory used by setup.py

    docs\  # mainly documentation, right?

    setup.py # setup for the project, as suggested in the above link

    project\   
        __init__.py
        module.py

        c_package\
            __init__.py
            file.c
            file.so
            other_c_stuff.c
            header.h

        tests\
            __init__.py
            test_bla.py

所以在 project 包及其子包中,如果你就地构建 C 扩展,你可以使用相对导入

python setup.py build_ext --inplace

或创建一个包含

setup.cfg
[build_ext]
inplace=True

但仅用于开发,请勿发布,否则会安装失败。

构建自动化是可能的,但除了 C 源代码发生变化时直接调用 setup.py 之外,我不知道还有什么。