繁体   English   中英

Python 导入错误。 如何在包之间导入模块?

[英]Python ImportError. How can I import modules among packages?

我正在使用这种类型的文件夹树进行项目:

-main.py

  -Message_handlers
     -__init__.py
     -On_message.py
     -Other_modules.py
  
  -Exceptions_handler
     -__init__.py
     -Run_as_mainException.py

Message_handlersExceptions_handler是两个包,现在我的问题是,我无法使用此代码从模块On_message.py中导入 class Run_as_mainException(在模块Run_as_mainException.py内部)

# This is On_message.py
from ..Exceptions_handler.Run_as_mainException import Run_as_main_Exception

此行给出错误: ImportError: attempted relative import with no known parent package

ps 每个文件里面都有一个class 和文件同名,例子:

# This is Run_as_mainExample.py
class Run_as_mainExample:
    def __init__(self):
        # rest of the code

谁能帮帮我吗?

您必须假设您正在从 main.py 所在的级别运行所有内容。 这意味着,假设您执行python main.py ,并且您想要从main.py导入Run_as_main_Exception ,您应该怎么做?

from Exceptions_handler.Run_as_mainException import Run_as_main_Exception

尝试在 On_message.py 文件中使用该行,从该确切位置运行脚本时应该不会有任何问题(请记住,与 main.py 所在的级别相同)

暂无
暂无

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

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