从另一个目录导入 [英] Import from another directory

查看:61
本文介绍了从另一个目录导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从另一个目录中的另一个导入.py文件(从app1导入app2)所以有目录树

I need to import .py file from another one in another directory (import app2 from app1) So there is directory tree

app:
    dir1:
        app1.py
    dir2:
        app2.py

我的问题几乎类似于从另一个目录导入,但是此解决方案对我不起作用由于某些原因

My problem is almost like Importing from another directory, but this solution doesnt work for me for some reason

此外,我一直在尝试这样做(app1.py)

Furthermore i've been trying to do like this (app1.py)

from ..dir2 import app2

错误是:尝试了相对顶级包之外的相对导入

The error is: Attempted relative import beyond top-level package

我该如何解决?

推荐答案

将其他目录添加到系统路径

Add your additional directories to the system path

import sys
sys.path.insert(0, "/path/to/app1/dir2")
sys.path.insert(0, "/path/to/app2/dir2")

这篇关于从另一个目录导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆