attempted relative import beyond top-level package with boost/Python

南楼画角 提交于 2020-08-11 01:14:07

问题


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

in foo.py, I have some code that imports from mylib.py:

from ..mylib import MyLib
class Foo:
    # code

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);
}

And this gave me an error:

    from ..mylib import MyLib
ValueError: attempted relative import beyond top-level package

How can I fix this?

Thanks

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

回答1:


Your path on Linux should be "/home/username/projectfiles/project/utilities/foo.py". You are missing the first /.




回答2:


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++.



来源:https://stackoverflow.com/questions/63060211/attempted-relative-import-beyond-top-level-package-with-boost-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!