简体   繁体   English

从 python 中的子目录导入文件时出错

[英]Error importing files from a sub directory in python

I have made a small programming language and seperated the Lexer, Parser, and Interpreter into different files.我制作了一种小型编程语言,并将 Lexer、Parser 和 Interpreter 分离到不同的文件中。 Now I would like those files to be in a sub directory Source.现在我希望这些文件位于子目录 Source 中。 I have Shell.py that uses them.我有使用它们的 Shell.py。 In short, this is the structure.简而言之,这就是结构。

Language -{
   Source -{
       Main.py
       Lexer.py
       Parser.py
       Interpréter.py
   Shell.py

In shell.py, I want to import main.py, which in turn imports the Lexer, parser, and interpreter.在 shell.py 中,我想导入 main.py,它依次导入 Lexer、解析器和解释器。

So:所以:

#Shell.py
import Source.Main
Main.run(some code)

#Main.py
from Lexer import Lexer
.... Parser
.... Interpreter

When I run Main.py everything works, but when I run Shell.py it comes up with this:当我运行 Main.py 时,一切正常,但是当我运行 Shell.py 时,它会出现:

File Source/Main.py, line 1 in <module>
    from Lexer import Lexer
ImportError: No module named ‘Lexer’

EDIT: There is an _ init_ .py in the Source directory.编辑:源目录中有一个 _ init_ .py 。 I am not trying to import multiple files from the sub directory, just one that procedes to import others.我不是要从子目录中导入多个文件,而只是导入其他文件。

Importing a file does not automatically import all the packages you imported in the file.导入文件不会自动导入您在文件中导入的所有包。 Basically, when you imported Main.py, you didn't import the packages that Main.py imports.基本上,当您导入 Main.py 时,您并没有导入 Main.py 导入的包。 You need to manually import all of the packages in that folder.您需要手动导入该文件夹中的所有包。

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

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