从 Python 中的相邻文件夹导入模块 [英] Importing modules from a neighbouring folder in Python

查看:56
本文介绍了从 Python 中的相邻文件夹导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我把问题放在下图中:

编辑图旁边的问题是:

如何让 script_A1 从 script_B2 导入函数?

How do I make script_A1 import a function from script_B2?

之前有人问过类似的问题.但大多数答案都建议将模块/脚本/包(无论)添加到 PATH 变量中.例如:

Similar questions have been asked before. But most answers suggest to add the module/script/package(whatever) to the PATH variable. For example:

sys.path.append('...')

但是将模块添加到 PATH 变量感觉非常错误.我不想以任何方式改变我的系统.当我的应用程序关闭时,我希望我的 Python 环境干净且未受影响".我担心在我的系统上向 PATH 变量添加不受控制的模块会导致以后头痛.

But adding the module to the PATH variable just feels so wrong. I do not want to alter my system in any way. When my application closes, I want my Python environment to be clean and 'untouched'. I'm afraid that adding uncontrolled modules to the PATH variables on my system will cause headaches later on.

谢谢你帮助我:-)

推荐答案

你可以使用一个把顶级文件夹添加到路径的技巧:

You can use a trick of adding the top folder to path:

import sys
sys.path.append('..')
import folderB.something

如果您愿意,也可以使用 imp.load_source.

You can also use imp.load_source if you prefer.

这篇关于从 Python 中的相邻文件夹导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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