系统错误:未加载父模块“”,无法执行相对imp

2024-04-25 23:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下目录:

myProgram
└── app
    ├── __init__.py
    ├── main.py 
    └── mymodule.py

mymodule.py版本:

class myclass(object):

def __init__(self):
    pass

def myfunc(self):
    print("Hello!")

主.py:

from .mymodule import myclass

print("Test")
testclass = myclass()
testclass.myfunc()

但是当我运行它时,我会得到这个错误:

Traceback (most recent call last):
  File "D:/Users/Myname/Documents/PycharmProjects/myProgram/app/main.py", line 1, in <module>
    from .mymodule import myclass
SystemError: Parent module '' not loaded, cannot perform relative import

这是有效的:

from mymodule import myclass

但是,当我输入这个时,没有自动完成,并且有一条消息:“unresolved reference:mymodule”和“unresolvedreference:myclass”。 在我正在进行的另一个项目中,我得到了一个错误:“importorror:没有名为‘my module’的模块。

我能做什么?


Tags: frompyimportselfappinitmaindef
3条回答

我通常使用这种解决方法:

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

这意味着您的IDE应该选择正确的代码位置,python解释器将设法运行您的代码。

如果您只是在app下运行main.py,只需导入

from mymodule import myclass

如果要在其他文件夹上调用main.py,请使用:

from .mymodule import myclass

例如:

├── app
│   ├── __init__.py
│   ├── main.py
│   ├── mymodule.py
├── __init__.py
└── run.py

main.py

from .mymodule import myclass

运行.py

from app import main
print(main.myclass)

所以我认为你的主要问题是如何调用app.main

我也有同样的问题,我用绝对导入而不是相对导入来解决。

例如,在您的案例中,您将编写如下内容:

from app.mymodule import myclass

你可以在documentation中看到。

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

相关问题 更多 >