简体   繁体   English

我的自定义模块的导入无法解决

[英]Import of my custom module could not be resolved

I've done some searching, but nothing either works or applies to this specific case.我已经进行了一些搜索,但没有任何方法适用于这种特定情况。

I have a file structure like this:我有这样的文件结构:

- my_project
   - app.py
   - my_project
      - services
         - begin.py
         - data_analysis.py
         - model_creation.py
         - output.py

and I am trying to simply import each of the modules into the app.py file so I can run a flask application, but I keep getting an import with only one of the imports (and it is always the same one).我试图简单地将每个模块导入到app.py文件中,这样我就可以运行 flask 应用程序,但我一直只导入一个导入(并且始终是同一个)。 For example, if I ran python app.py , I would get:例如,如果我运行python app.py ,我会得到:

File "C:\Users\me\my_project\app.py", line 9, in <module>
    from my_project.services.data_analysis import analyze
ModuleNotFoundError: No module named 'my_project.services.data_analysis'

I would think it has to do with relative imports or something, only its just one of the files that is having the issue, not several/all of the files.我认为它与相对导入或其他东西有关,只是它只是有问题的文件之一,而不是几个/所有文件。 Any ideas on why I'm getting this error?关于我为什么会收到此错误的任何想法?

EDIT: modified project structure.编辑:修改项目结构。

EDIT 2: this is unique as when running app.py, it still allows for things such as from.my_project.begin import start or from my_project.model_creation import create , but no relative or non-relative import will work for just the data_analysis.py module.编辑 2:这是独一无二的,因为在运行 app.py 时,它仍然允许诸如from.my_project.begin import startfrom my_project.model_creation import create之类的东西,但没有相对或非相对导入适用于data_analysis.py模块。

add __init__.py files to your directories and subdirectories.__init__.py文件添加到您的目录和子目录中。 It tells python to treat directories as modules.它告诉 python 将目录视为模块。

example:例子:


• my_project
   - app.py
   • my_project
      • services
         - __init__.py
         - begin.py
         - data_analysis.py
         - model_creation.py
         - output.py

In app.py:在 app.py 中:

from my_project.services.data_analysis import analyze 

I'm under the impression that services is a directory inside the second my_project folder.我的印象是 services 是第二个 my_project 文件夹中的一个目录。 if it's not, then you would import like so from services.data_analysis import analyze如果不是,那么您将像这样from services.data_analysis import analyze

For whatever reason, it just wasn't working for that one specific module.无论出于何种原因,它只是不适用于那个特定的模块。 I ended up copying the file and deleting the original, and now it works fine.我最终复制了文件并删除了原始文件,现在它可以正常工作了。 Not sure why or how, but it works now.不知道为什么或如何,但它现在有效。

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

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