如何导入导入本地模块的远程模块?

我的程序使用importlib.

这个导入的模块(我们称之为A)导入位于它旁边的一些其他自定义模块(我们称之为B)。


My_Project\

    │

    └─── my_program.py


Some_Other_Location\

    │

    ├─── A_module_my_program_wants_to_import.py

    └─── B_module_A_imports.py

当我导入A 而不导入B时,它工作得很好:


# Sample from my_program.py


path = Some_Other_Location\A_module_my_program_wants_to_import.py

spec = importlib.util.spec_from_file_location("A", path)

module = importlib.util.module_from_spec(spec)

spec.loader.exec_module(module)

但是,当在A我导入B:


# Sample from A_module_my_program_wants_to_import.py


import B_module_A_imports

或者


from B_module_A_imports import foo

我运行我的程序,我得到:


Build error: No module named 'B_module_A_imports'

回溯到我在程序中导入的位置,以及


我试过指定submodule_search_locations=Some_Other_Location,spec_from_file_location但没有帮助。


所以问题是如何导入远程模块,即导入本地模块?


慕仙森
浏览 153回答 1
1回答

绝地无双

我找到了一种解决方法,但不是一个合适的解决方案。解决方法如下:我已经意识到它正在尝试加载my_program 所在的 B 并且显然没有找到任何东西。但是,可以通过Some_Other_Location添加sys.path. 所以这就是 my_program 的导入部分的样子:directory = Some_Other_Locationsys.path.append(directory)path = Some_Other_Location\A_module_my_program_wants_to_import.pyspec = importlib.util.spec_from_file_location("A", path)module = importlib.util.module_from_spec(spec)spec.loader.exec_module(module)sys.path.remove(directory)这工作得很好,但是,我仍然愿意接受实际的解决方案!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python