简体   繁体   English

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

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

I was working on a project with this type of folder tree:我正在使用这种类型的文件夹树进行项目:

-main.py

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

Message_handlers and Exceptions_handler are two packages, now my problem is that from inside the module On_message.py I can't import the class Run_as_mainException (inside of the module Run_as_mainException.py ) using this code 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

This line gives the error: ImportError: attempted relative import with no known parent package此行给出错误: ImportError: attempted relative import with no known parent package

ps Every file has a class inside with the same name of the file, example: ps 每个文件里面都有一个class 和文件同名,例子:

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

Can anyone help me please?谁能帮帮我吗?

You have to assume that you're running everything from the level where main.py is located.您必须假设您正在从 main.py 所在的级别运行所有内容。 This means, imagine that you execute python main.py , and you want to import Run_as_main_Exception from main.py , what should you do?这意味着,假设您执行python main.py ,并且您想要从main.py导入Run_as_main_Exception ,您应该怎么做?

from Exceptions_handler.Run_as_mainException import Run_as_main_Exception

Try using that line in your On_message.py file, and you shouldn't have any problem when running your script from that exact location (remember, the same level where main.py is located)尝试在 On_message.py 文件中使用该行,从该确切位置运行脚本时应该不会有任何问题(请记住,与 main.py 所在的级别相同)

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

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