一个用 python 编写的项目,带有一些 C 扩展(不使用 SWIG 等)。我正在尝试弄清楚如何构建我的项目,以便:
- 导入工作。导入共享对象
- 我不需要更改 PYTHONPATH(尝试弄清楚但失败了)。
- 将来,分发项目包将是最简单的。
按照建议,当前结构是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 中无效。理想的答案将解决以下问题:
- 建议的项目结构。
- 如何执行导入(例如,从
tests
中的模块)。 - 我应该(可以)将所有 C 文件保存在单独的库中吗?
- C 文件的构建是在哪个
setup.py
文件中完成的(我应该将它们发布在这里吗?) - 是否可以在必要时自动构建?怎么样?
我试过了 relative imports - 由于某种原因,它们对我不起作用。 我看到了对 this 的接受答案问题。他说——做任何事。但我无法让进口工作。我读了this回答,但不知道他拥有的所有东西是什么(而我没有)。接受的答案对我没有帮助,因为再次导入失败。 This博客文章提供了很好的建议,但是,再次,进口!
最佳答案
我不想详细说明一般性答案,因为您已经链接到好的答案。
一些适合您的结构可能如下所示:
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
之外,我不知道还有什么其他方法。
关于具有 C 扩展的 Python 项目 - 结构、导入和测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618289/