简体   繁体   English

Python 无法导入模块

[英]Python not able to import module

I have quite a number of different file which I want to use to create an API.我有很多不同的文件,我想用它们来创建 API。 The files are:这些文件是:

  1. app.py -- main file app.py -- 主文件
  2. utils.py -- utilities file utils.py -- 实用程序文件
  3. recorder.py记录器.py
  4. consts.py常量.py
  5. submitter.py提交者.py

All of these files have a dependency on one another.所有这些文件都相互依赖。 However, when I try to import them in a particular file ( for ex - importing consts in recorder.py, I am getting error saying The module consts is not found. I am importing it using:但是,当我尝试将它们导入特定文件时(例如,在 recorder.py 中导入 consts,我收到错误消息说找不到模块 consts。我正在使用以下方法导入它:

from .consts import consts 

Can someone tell me what am I doing wrong here, and how to solve this issue.有人可以告诉我我在这里做错了什么,以及如何解决这个问题。

If i import it in the main app.py, it doesn't give any error.如果我在主 app.py 中导入它,它不会给出任何错误。 but it does when I want to access any consts in other files.但是当我想访问其他文件中的任何常量时它确实如此。

Thank you in advance先感谢您

EDIT: Here is the folder structure:编辑:这是文件夹结构:

在此处输入图像描述

When you say they are interdependent, that may be your issue.当您说它们相互依赖时,这可能是您的问题。 You cannot have two files that depend directly on one another with out some hacky solutions as youll run into the problem of importing one that tries to import the importer which tries to import the importee and so on forever.如果没有一些 hacky 解决方案,您不能拥有两个直接相互依赖的文件,因为您将遇到导入一个尝试导入导入器的问题,该导入器尝试导入导入者,以此类推。

Edit: i misunderstood how imports work, the problem comes from:编辑:我误解了导入的工作原理,问题来自:

"If you import X from your main program, Python will load the code for X and execute it. When Python reaches the import Y statement, it loads the code for Y, and starts executing it instead. “如果您从主程序导入 X,Python 将加载 X 的代码并执行它。当 Python 到达 import Y 语句时,它会加载 Y 的代码,并开始执行它。

At this time, Python has installed module objects for both X and Y in sys.modules.此时,Python 已经在 sys.modules 中安装了 X 和 Y 的模块对象。 But X doesn't contain anything yet;但是 X 还没有包含任何东西; the def spam statement hasn't been executed." def spam 语句尚未执行。”

As stated in the link i included at the bottom of this response.正如我在此回复底部包含的链接中所述。 The link also gives some possible solutions like changing when you import the different modules.该链接还提供了一些可能的解决方案,例如在导入不同模块时进行更改。

What we really need is to see the code for the files to understand how you are importing everything我们真正需要的是查看文件的代码以了解您如何导入所有内容

this link should help you in your desire for circular dependency. 这个链接应该可以帮助您实现循环依赖的愿望。

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

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