在Python中嵌套导入的问题

huangapple go评论71阅读模式
英文:

Trouble with nested imports in python

问题

我正在用Python编写一个项目,但在导入方面遇到了很大的麻烦。我的项目包括许多脚本,我一直在尝试编写一个GUI,允许用户按需运行任何脚本。为了实现这一点,我创建了一个用于存放脚本的目录,其中包含每个具体脚本的子目录。我还有一个名为gui的单独目录,其中包含一个Python文件,用于导入每个脚本并运行它。文件结构如下所示。

scripts/
       script1/
              file1.py
              file2.py
              main.py
gui/
   gui.py

在gui.py文件中,我有:

from scripts.script1.main import main as script1

在main.py文件中,我有:

from file1 import function1
from file2 import function2

当我运行gui.py文件时,main.py会被按预期导入,但我会收到以下错误:

ModuleNotFoundError: No module named 'file1'

无论何时运行代码,我都会遇到这个问题。我不太确定为什么会发生这种情况以及如何修复它。如果我打印sys.path,它会包括项目的根目录,但不包括任何子目录。这里发生了什么?谢谢!

英文:

I am writing a project in python and have been having major trouble with imports. My project consists of a number of scripts, and I have been trying to write a gui that will allow the user to run any of the scripts on demand. In order to do this, I have created a directory for the scripts, with a sub-directory for each specific script. I have a seperate directory called gui, with a python file that is meant to import each script and run it. The file structure is as follows.

scripts/  
       script1/  
              file1.py  
              file2.py  
              main.py  
gui/  
   gui.py  

In the gui.py file I have:

from scripts.script1.main import main as script1

and in the main.py file I have:

from file1 import function1  
from file2 import function2

When I run the gui.py file, main.py is imported as intended, but I get:

ModuleNotFoundError: No module named 'file1'

whenever I run the code.
I'm not really sure why this happens and how to fix it. If I print sys.path it includes the root directory for the project, but none of the subdirectories. What's happening here? Thanks!

答案1

得分: 1

已解决。

我将嵌套的导入更改为:

from .file1 import function1
from .file2 import function2

这个方法有效。我仍然不明白为什么。

英文:

Solved.

I changed the nested imports to:

from .file1 import function1
from .file2 import function2

This works. I still do not understand why.

答案2

得分: -1

你必须创建一个Python文件,并在主文件中导入它。

英文:

Hi you must make the python file and import it in your main file

huangapple
  • 本文由 发表于 2023年7月13日 17:33:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定