我有一个模块 modA
,它包含一个合成子模块 modB
(使用 PyModule_New
创建);现在导入模块:
from modA import modB
可以导入 modA.modB
失败。
我错过了什么?
modA.cpp(使用
boost::python
,但它很可能与纯 python 的 c-API 相同):#include<boost/python.hpp> namespace py=boost::python; BOOST_PYTHON_MODULE(modA){ py::object modB=py::object(py::handle<>(PyModule_New("modB"))); modB.attr("__file__")="<synthetic>"; py::scope().attr("modB")=modB; };
编译(g++ 而不是 clang++ 效果相同)
clang++ -o modA.so modA.cpp -fPIC -shared -lboost_python `pkg-config python --cflags --libs`
测试.py:
import sys sys.path.append('.') from modA import modB import modA.modB
python test.py
(注意第一个导入没问题,第二个导入失败了):Traceback (most recent call last): File "test.py", line 4, in <module> import modA.modB ImportError: No module named modB
最佳答案
感谢this answer , 我找到了解决方案,它包含在 sys.modules['modA.modB']=modB
中,但是在模块初始化函数中用 c++ 编写:
#include<boost/python.hpp>
namespace py=boost::python;
BOOST_PYTHON_MODULE(modA){
py::object modB=py::object(py::handle<>(PyModule_New("modA.modB")));
modB.attr("__file__")="<synthetic>";
py::scope().attr("modB")=modB;
// this was the missing piece: sys.modules['modA.modB']=modB
py::extract<py::dict>(py::getattr(py::import("sys"),"modules"))()["modA.modB"]=modB;
};
关于python - 合成子模块 : from A import B (ok) vs. 导入 A.B(错误)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11063243/