我有以下目录结构,我是 python 的新手。在文件夹 bin 中,我有一个文件“script.py”,我想在其中从代码包中导入“module.py”。我在 stackoverflow 上看到过许多针对此问题的解决方案,涉及修改 sys-path 或提供完整路径名。有什么方法可以使用相对有效的导入语句而不是指定完整路径来导入它们?
project/
bin/
script.py
code/
module.py
__init__.py
最佳答案
确保bin/script.py
可以在不配置环境的情况下运行,将此序言添加到script.py
之前 from code import module
线 (
来自 twisted/bin/_preambule.py
):
# insert `code/__init__.py` parent directory into `sys.path`
import sys, os
path = os.path.abspath(sys.argv[0]) # path to bin/script.py
while os.path.dirname(path) != path: # until top-most directory
if os.path.exists(os.path.join(path, 'code', '__init__.py')):
sys.path.insert(0, path)
break
path = os.path.dirname(path)
while
循环是为了支持从bin/some-other-directory/.../script.py
开始运行
关于python - Python 中的相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821968/