【问题标题】:ImportError while importing module from another folder [duplicate]从另一个文件夹导入模块时出现 ImportError [重复]
【发布时间】:2016-06-26 13:22:06
【问题描述】:

我有以下文件夹结构:

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 执行相同的导入并且它工作正常。

【问题讨论】:

  • 你的模块树中的orkit在哪里?
  • 用正确的名字编辑了名字。
  • 试试sys.path.append('/home/other/folder/')
  • 您应该导入reactive 并在__init__.py 文件中定义control。您可以执行sys.path.insert(0, '/path/to/controller/,然后执行import reactive 并通过reactive.control() 进行呼叫控制。
  • @LutzHorn sys.path.insert(0, ...) 而不是通过PATH 中的早期存在来避免覆盖所需功能的其他东西。免责声明这可能会破坏内置:)

标签: python


【解决方案1】:

在 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 的内置函数冲突的任何内容,则会破坏这些内置函数,这可能会导致各种问题。因此,尽量使用导入机制,并回退到跨版本的方式。

【讨论】:

  • 如果反对者看到这一点,请解释我的帖子有什么问题。
猜你喜欢
  • 2019-05-20
  • 2020-09-09
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 2021-10-23
  • 2019-08-16
  • 2016-05-18
  • 1970-01-01
相关资源
最近更新 更多