【问题标题】:Python project with C extensions - structure, imports and tests带有 C 扩展的 Python 项目 - 结构、导入和测试
【发布时间】:2015-04-21 12:01:22
【问题描述】:

一个用 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 中的 by 模块)。
  3. 我应该(可以)将所有 C 文件保存在单独的库中吗?
  4. C 文件的构建在 setup.py 文件中的哪个文件中完成(我应该将它们发布在这里吗?)
  5. 是否可以在必要时自动构建?怎么样?

我试过relative imports - 由于某种原因它们对我不起作用。 我看到了对this 问题的接受回答。他说——随便吧。但我无法让导入工作。我阅读了this 的答案,但不知道他拥有的所有东西是什么(而我没有)。接受的答案对我没有帮助,因为导入再次失败。 This 博客文章提供了很好的建议,但同样是导入!

【问题讨论】:

    标签: python c python-2.7 import directory-structure


    【解决方案1】:

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

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

    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 之外不知道有什么其他方法。

    【讨论】:

      猜你喜欢
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 2016-04-16
      • 2013-01-04
      相关资源
      最近更新 更多