简体   繁体   English

python 从不同文件夹导入 class

[英]python import class from different folder

my project has folders that are structured like this:我的项目有结构如下的文件夹:

main
 -folder 1
  -file1.py
 -folder 2
  -file2.py

both file1 and file2 having classes. file1 和 file2 都有类。 when I try from main.folder1.file1 import class1 it fails, saying "No module named main".当我尝试from main.folder1.file1 import class1时它失败了,说“没有名为 main 的模块”。 What am I doing wrong and how should I import it?我做错了什么,我应该如何导入它?

In python you have to declare each folder as a module by adding a file named __init__.py in each directory including the root.在 python 中,您必须通过在每个目录(包括根目录)中添加一个名为__init__.py的文件来将每个文件夹声明为一个模块。 This file can be empty.该文件可以为空。

you can do this if there are one level above.如果上面有一个级别,你可以这样做。

import sys
sys.path.insert(0,'../folder1')
sys.path.insert(0,'../folder2')
import function1
import function2
....

Once you run the first 3 lines, you are adding those folders to the working directory.运行前 3 行后,您就将这些文件夹添加到工作目录中。 You can then import the functions within those files as if they are in the file already.然后,您可以在这些文件中导入函数,就好像它们已经在文件中一样。

If the folders are in the same level, do this,如果文件夹在同一级别,请执行此操作,

import sys
sys.path.insert(0,'folder1')
sys.path.insert(0,'folder2')
import function1
import function2
....

you have to first create the module by including __init__.py in the root directory which is same in the hierarchy of main folder and also create an __init__.py in other sub folders to make them accessible as modules.您必须首先通过在与主文件夹层次结构相同的根目录中包含__init__.py来创建模块,并在其他子文件夹中创建一个__init__.py以使它们可以作为模块访问。 Here is an example structure from the official documentation.Note how at each level there is __init__.py you have to include similarly.这是官方文档中的示例结构。请注意在每个级别如何有__init__.py您必须类似地包含。

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
    moduleA.py

your structure can be like below:您的结构可以如下所示:

main/
    __init__.py
    folder1/
        __init__.py
        file1.py
    folder2/
        __init__.py
        file2.py

Then you can append the path to the module at the top level like below.然后你可以 append 到顶层模块的路径,如下所示。 You can have it in the __init__.py in the root directory.你可以把它放在根目录的__init__.py中。

sys.path.append(path.dirname(path.dirname(path.abspath( file )))) sys.path.append(path.dirname(path.dirname(path.abspath(文件))))

Then try accessing like from folder1.file1 import class1 .然后尝试访问from folder1.file1 import class1 This should resolve your problem.这应该可以解决您的问题。

To further understand your problem read about modules and how to include relative imports by referring documentation .要进一步了解您的问题,请阅读有关modules以及如何通过参考文档来包含relative imports的信息。

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

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