从另一个文件夹导入模块时出现ImportError错误。
从另一个文件夹导入模块时出现ImportError错误。
这个问题已经在这里有了答案:
我有以下文件夹结构:
controller/ __init__.py reactive/ __init__.py control.py pos/ __init__.py devices/ __init__.py cash/ __init__.py server/ __init__.py my_server.py dispatcher/ __init__.py dispatcherctrl.py
我需要在 my_server.py
中导入模块 control.py
,但是它报错了 ImportError: No module named controller.reactive.control
,尽管我已经在所有文件夹中都添加了 __init__.py
文件,并在 my_server.py
中添加了 sys.path.append(\'/home/other/folder/controller/reactive\')
。
主文件在 my_server.py
中。
我不明白为什么会这样,因为 dispatcherctrl.py
做同样的导入并且可以正常工作。
admin 更改状态以发布 2023年5月21日
在Python3中
您可以使用importlib.machinery模块为导入创建名称空间和绝对路径:
import importlib.machinery loader = importlib.machinery.SourceFileLoader('control', '/full/path/controller/reactive/control.py') control = loader.load_module('control') control.someFunction(parameters, here)
这种方法可以用于以任何方式在任何文件夹结构中导入东西(向后,递归,不太重要,我在这里使用绝对路径只是为了确保)。
Python2
感谢Sebastian为Python2提供了类似的答案:
import imp control = imp.load_source('module.name', '/path/to/controller/reactive/control.py') control.someFunction(parameters, here)
跨版本方式
您也可以执行以下操作:
import sys sys.path.insert(0, '/full/path/controller') from reactive import control # <-- Requires control to be defined in __init__.py # it is not enough that there is a file called control.py!
重要说明!将您的路径插入sys.path
的开头可以正常运行,但如果您的路径包含与Python内置函数冲突的内容,您将破坏这些内置函数,可能会导致各种问题。因此,请尽可能使用导入机制,并回退到跨版本方式。