问题描述
我已经尝试了多种方法来在帖子,但是我决定发布一个新问题,因为该帖子的内容是关于boost找不到模块的问题.这是文件夹的结构:
I've tried multiple ways to import a module in a post here, but I decided to post a new question since that post was about boost not being able to find the module. Here's the structure of the folder:
project
|__ utilities
| |__ foo.py
|
|__ boost_extensions
| |__ myclass.cpp
| |__ myclass.so
|
|__ someotherstuff
| |__ bar.py
|
|__ mylib.py
|
|__ __main__.py
在foo.py中,我有一些代码是从mylib.py导入的:
in foo.py, I have some code that imports from mylib.py:
from ..mylib import MyLib
class Foo:
# code
在myclass.cpp中,我找不到使用相对路径导入Foo的方法,因此我使用了绝对路径(灵感来自帖子):
in myclass.cpp, I could not find a way to import Foo using a relative path, so I used an absolute path (inspired from an answer to the post here):
boost::python::object mod;
void set_global(){
boost::python::object importlib_util = import("importlib.util");
boost::python::object spec = \
importlib_util.attr("spec_from_file_location")("module.name",\
"/home/username/projectfiles/project/utilities/foo.py");
boost::python::object foo = importlib_util.attr("module_from_spec")(spec);
mod = spec.attr("loader").attr("exec_module")(foo);
}
这给了我一个错误:
from ..mylib import MyLib
ValueError: attempted relative import beyond top-level package
我该如何解决?
谢谢
edit:不确定是否相关,但是如果我打印变量__name__
,则始终为module.name
,无论我在代码中输入了什么
edit : not sure if this is relevant or not but if I print the variable __name__
it's always module.name
, regardless of what I put in the code
# with ..utilities.foo instead of module.name in the function
# importlib_util.attr("spec_from_file_location")("module.name",\
# "home/username/projectfiles/project/utilities/foo.py");
print(__name__)
from ..mylib import MyLib
#output : module.name
推荐答案
我发布了一个类似的问题,并为此提出了解决方案也可以在这里工作(这是关于尝试通过使用相对路径在C ++中导入python模块,我对此发表了另一篇文章,因为它给出了完全不同的错误).基本上,我将模块加载到python中,并将其作为参数传递给C ++.
I posted a similar question and the solution for that works here too (it was about trying to import a python module in C++ by using a relative path, I made a different post about it because it gave a completely different error). Basically I loaded the module in python and passed it as an argument to C++.
这篇关于尝试通过boost/Python相对于顶级包的相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!