简体   繁体   English

当我尝试导入 package 时出现 ModuleNotFoundError

[英]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 并将controllersmodels作为不同的模块。

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
  • The content of 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 app应用程序内的python3 -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.您似乎在appcontroller文件夹以及正确的导入路径中缺少__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...但现在,我希望你能得到解决方案......

Output Output

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.

相关问题 PYTHON -- ModuleNotFoundError:当我尝试导入时没有名为“playsound”的模块 package - PYTHON -- ModuleNotFoundError: No module named 'playsound' when i am trying to import package 尝试导入 package 时出现 python ModuleNotFoundError - python ModuleNotFoundError when trying to import a package 尝试导入时的 ModuleNotFoundError 和 ImportError 可以 package - ModuleNotFoundError and ImportError when trying to import can package 尝试从导入的包中导入模块时出现“ModuleNotFoundError” - 'ModuleNotFoundError' when trying to import module from imported package Python:尝试从同一 package 导入模块时出现“ModuleNotFoundError” - Python: 'ModuleNotFoundError' when trying to import module from the same package 尝试使用软件包时出现ModuleNotFoundError - ModuleNotFoundError when trying to use package 尝试导入 Tensorflow 时出现 ModuleNotFoundError - ModuleNotFoundError when trying to import Tensorflow 我导入枕头时出现ModuleNotFoundError - ModuleNotFoundError when I `import pillow` 无法导入我制作的包。 “模块未找到错误” - Impossible to import a package I made. "ModuleNotFoundError" 尝试安装和导入 aux 库时出现 ModuleNotFoundError - ModuleNotFoundError when trying to install and import the aux library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM