简体   繁体   English

在子文件夹中导入多个python文件

[英]Importing multiple python files in subfolders

I want to import a python file Loader within a subfolder sub1 . 我想在子文件夹sub1导入一个python文件Loader This file that I want to import, imports another file detector within that same subfolder. 我要导入的此文件,在同一子文件夹中导入另一个文件detector However, Loader gives the following error: 但是, Loader出现以下错误:

ModuleNotFoundError: No module named 'detector' ModuleNotFoundError:没有名为“检测器”的模块

I've tried using the exec command in Python and 我试过在python中使用exec命令,

import sub1.Loader

The folder structure looks like this: 文件夹结构如下所示:

Project
    | 
    +-- File_for_loading_Loader.py
    | 
    +-- sub1
         |  
         +-- __init__.py
         +-- Loader.py
         +-- detector.py

Can anyone help? 有人可以帮忙吗?

Edit 编辑

I now use: 我现在使用:

    import subprocess
    subprocess.call(["python", "Loader.py"], cwd="sub1")

which does the trick nicely. 这很好地完成了技巧。 No need for relative imports etc. 无需相对进口等

Since you created sub1 as module you have to import files from it always like sub1.<module_name> . 由于您将sub1创建为模块,因此必须始终像sub1.<module_name>一样从其中导入文件。

So for you it should be from sub1.detector import detect_faces in your Loader. 因此,对于您来说,应该from sub1.detector import detect_faces Loader中的from sub1.detector import detect_faces

You need to import loader in File_for_loading_Loader.py by using import sub1.Loader as abc . 您需要通过使用import sub1.Loader as abcFile_for_loading_Loader.py导入加载程序。

And in Loader.py you need to import detector by using import sub1.detector as xyz . 在Loader.py中,您需要使用import sub1.detector as xyz来导入检测器。

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

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