“父模块”未加载,无法执行相对导入

我有以下目录:

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

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

但是当我输入这个时,没有得到自动完成,并且有一条消息: “未解决的引用: mymodule”和“未解决的引用: myclass”。 在我正在进行的另一个项目中,出现了这样的错误: “ Import Error: No module name‘ mymodule’。

我能做什么?

135502 次浏览

I usually use this workaround:

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

Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.

I had the same problem and I solved it by using an absolute import instead of a relative one.

for example in your case, you may write something like this:

from app.mymodule import myclass

You can see in the 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.

Edit: If you encounter this error ImportError: No module named 'app.app'; 'app' is not a package, remember to add the __init__.py file in your app directory so that the interpreter can see it as a package. It is fine if the file is empty.

If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.

if you just run the main.py under the app, just import like

from mymodule import myclass

if you want to call main.py on other folder, use:

from .mymodule import myclass

for example:

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

main.py

from .mymodule import myclass

run.py

from app import main
print(main.myclass)

So I think the main question of you is how to call app.main.