简体   繁体   English

尝试使用 boost/Python 进行相对导入超出顶级 package

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

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.我已经尝试了多种方法在此处的帖子中导入模块,但我决定发布一个新问题,因为该帖子是关于 boost 无法找到该模块。 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:在 foo.py 中,我有一些从 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 ):在 myclass.cpp 中,我找不到使用相对路径导入 Foo 的方法,因此我使用了绝对路径(灵感来自对此处帖子的回答):

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编辑:不确定这是否相关,但如果我打印变量__name__它总是module.name ,不管我在代码中放了什么

# 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

Your path on Linux should be "/home/username/projectfiles/project/utilities/foo.py".您在 Linux 上的路径应该是“/home/username/projectfiles/project/utilities/foo.py”。 You are missing the first /.您缺少第一个 /。

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).我发布了一个类似的问题,并且该解决方案在这里也有效(它是关于尝试通过使用相对路径在 C++ 中导入 python 模块,我对此发表了不同的帖子,因为它给出了完全不同的错误)。 Basically I loaded the module in python and passed it as an argument to C++.基本上我在 python 中加载了模块并将其作为参数传递给 C++。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM