[英]ModuleNotFoundError when I am trying to import package
my_controller.py is as follow: my_controller.py 如下:
from models import Person
david = Person('David')
And my project structure is我的项目结构是
app
├── controller
│ └── my_controller.py
│
└── models
└── __init__.py
└── person.py
I must do something wrong because I keep get我必须做错事,因为我一直得到
ModuleNotFoundError: No module named 'models'
What is the correct way to import class Person to my_controller.py?将 class Person 导入 my_controller.py 的正确方法是什么?
PS I am working on ubuntu PS我正在研究ubuntu
You need to use relative import您需要使用相对导入
from . import models
Or it's better to import models that you will user, since it won't visually collide with django.db.models.或者最好导入您将使用的模型,因为它不会在视觉上与 django.db.models 发生冲突。
from django import forms
from .models import VolunteerBasicInfo
class BasicInfoCollectionForm(forms.ModelForm):
class Meta:
model = VolunteerBasicInfo
...
You also don't need to user brackets with class Meta
.您也不需要使用 class
Meta
用户括号。
I am assuming that you have app
as a package and controllers
and models
as different modules.我假设您将
app
作为 package 并将controllers
和models
作为不同的模块。
To implement the package structure, you need to have __init__.py
in the root that is app
here and __init__.py
inside every module.要实现 package 结构,您需要在
app
的根目录中添加__init__.py
,在每个模块中添加__init__.py
。
After that, you can import one module functions/classes inn other modules without the need of relative import.之后,您可以在其他模块中导入一个模块函数/类,而无需相对导入。
I tested the same structure that is present in the question with above suggestion.我用上述建议测试了问题中存在的相同结构。
The structure looks like this:结构如下所示:
├── app
├── __init__.py
├── controllers
├── __init__.py
├── my_c.py
└── models
├── __init__.py
└── my_m.py
All the __init__.py
are empty.所有的
__init__.py
都是空的。
The content of my_m.py
is: my_m.py
的内容是:
class Person:
def test_model(self):
x = "Model Imported"
return x
my_c.py
is: my_c.py
的内容是:from models.my_m import Person
test = Person()
print(test.test_model())
When you execute:当你执行:
python3 -m controllers.my_c
inside apppython3 -m controllers.my_c
Output is: Output 是:
Model Imported
Let me know if it helps.让我知道它是否有帮助。
If you don't want to change any of the structure and you want to execute my_controller.py
you will need to append access to the common folder so it can import any of the adjacent modules.如果您不想更改任何结构并且想要执行
my_controller.py
,则需要 append 访问公共文件夹,以便它可以导入任何相邻的模块。
import sys
import os
sys.path.append(os.path.abspath(os.path.join(
os.path.dirname(__file__), '..')
))
from models.person import Person
x = Person()
If you're just running the file in the shell its pretty simple.如果您只是在 shell 中运行该文件,则非常简单。 The idea is you want to start it from what your "root" directory is in the project.
这个想法是你想从项目中的“根”目录开始。
First, add an empty __init__.py
file in the app/
directory.首先,在
app/
目录中添加一个空的__init__.py
文件。
Second, change your import in my_controller.py
to from models.person
, instead of just from models
:其次,将
my_controller.py
中的导入更改为from models.person
,而不仅仅是from models
:
from models.person import Person
david = Person('David')
Last, cd into the app/
directory, and run this bad boy.最后,cd 进入
app/
目录,然后运行这个 bad boy。
$ python3 -m controller.my_controller.py
If that doesn't work, then set your PYTHONPATH
to /app
as well, like so:如果这不起作用,请将您的
PYTHONPATH
也设置为/app
,如下所示:
export PYTHONPATH=$PYTHONPATH:/my/dir/app/venv/bin
and then attempt the first bash command again.然后再次尝试第一个 bash 命令。
If your folder structure is the following...如果您的文件夹结构如下...
app
├── __init__.py
│
├── controller
│ └── my_controller.py
│ └── __init__.py
│
└── models
└── __init__.py
└── person.py
And your root is the app
folder, you can use in my_controller.py
...你的根目录是
app
文件夹,你可以在my_controller.py
...
from app.models.person import Person
if __name__ == '__main__':
david = Person('David')
Then if you run the program in the shell, you first navigate to the parent folder of app
and use...然后如果你在 shell 中运行程序,你首先导航到
app
的父文件夹并使用...
PYTHONPATH=. python app/controller/my_controller.py
It seems you are missing a __init__.py
in the app
and the controller
folder as well as the correct import path.您似乎在
app
和controller
文件夹以及正确的导入路径中缺少__init__.py
。
Why using this approach为什么使用这种方法
__init__.py
files are necessary to treat the code in other folders as Python modules and allow for import. __init__.py
文件对于将其他文件夹中的代码视为 Python 模块并允许导入是必需的。 The if __name__ == '__main__':
is not necessary but good practise, read more eg here . if __name__ == '__main__':
不是必需的,而是很好的做法,请 在此处阅读更多信息。 Now you might ask yourself what does PYTHONPATH=.
现在你可能会问自己
PYTHONPATH=.
mean.意思是。 It sets the folder from where you execute your code as root.
它将执行代码的文件夹设置为 root。 Using that, you need
from <root>.<subfolder>.<file> import <class>
as import paths.使用它,您需要
from <root>.<subfolder>.<file> import <class>
作为导入路径。 This helps you keeping a clean import structure, that shows the full scope of your project and makes adding a tests
folder an ease:)这可以帮助您保持干净的导入结构,显示项目的完整 scope 并使添加
tests
文件夹变得容易:)
I hope I could help you!我希望我能帮助你!
Directory Structure like yours像你这样的目录结构
when I tried this out, at first I got the same error as yours and after many attempts of debugging it, I found out one of my _ init _ .py contains some unusual code that I didn't add and it was: from models import person
当我尝试这个时,起初我遇到了和你一样的错误,经过多次调试后,我发现我的一个_init _ .py 包含一些我没有添加的异常代码,它是:
from models import person
so when I removed it from there, It run successfully but only when I am running it from the root directory as shown in the image below.所以当我从那里删除它时,它运行成功,但只有当我从根目录运行它时,如下图所示。
Even I tried several ways to run it from current working directory by changing the cwd to "app" or in my case "practice" but then it started showing me an error ModuleNotFoundError: No module named 'app'
'甚至我尝试了几种方法从当前工作目录运行它,方法是将 cwd 更改为“app”或在我的情况下为“practice”,但随后它开始向我显示错误
ModuleNotFoundError: No module named 'app'
'
But for Now, I hope you get the solution...但现在,我希望你能得到解决方案......
Note:=you'll see several other files as well, It was added by my IDE or python itself.注意:=您还会看到其他几个文件,它是由我的 IDE 或 python 本身添加的。 so you don't need to worry about adding those files.
因此您无需担心添加这些文件。
code in my_controller.py:- my_controller.py 中的代码:-
from app.models import person
person.first()
and person.py module contains a function named first()并且 person.py 模块包含一个名为 first() 的 function
IDE USED:- PyCharm IDE 已使用:- PyCharm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.