如何从同级目录导入 Python 脚本? [英] How do I import a Python script from a sibling directory?

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

问题描述

假设我有以下目录结构:

Let's say I have the following directory structure:

parent_dir/
    foo_dir/
        foo.py
    bar_dir/
        bar.py

如果我想从 foo.py 中导入 bar.py,我该怎么做?

If I wanted to import bar.py from within foo.py, how would I do that?

推荐答案

如果所有出现的目录都是 Python packages,即它们都包含 __init__.py,那么你可以使用

If all occurring directories are Python packages, i.e. they all contain __init__.py, then you can use

from ..bar_dir import bar

如果目录不是 Python 包,您可以通过使用 sys.path 来做到这一点,但您不应该这样做.

If the directories aren't Python packages, you can do this by messing around with sys.path, but you shouldn't.

这篇关于如何从同级目录导入 Python 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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