如何从工作目录内外找到Python模块

2024-03-28 12:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python项目,其文件结构与此类似

├── project-folder
├── main_script.py
├── modules
│   ├── __init__.py
│   ├── helpers.py
│   ├── mod1.py
│   ├── mod2.py

main_script.py中,我使用来自mod1.pymod2.py的函数。既有{}又有{}{}。如果我直接运行mod1.py,它能够正确地找到helpers,但是当我运行main_script.py时,它抛出了一个ModuleNotFoundError: No module named 'helpers'

我可以通过在mod1.pymod2.py中添加以下任何一个来解决这个问题,但我想知道是否有更好的方法不需要我将此代码添加到modules中的每个模块中

方法1:

import sys
import os
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)

方法2:

try:
    import helpers 
except ModuleNotFoundError:
    from . import helpers

Tags: path方法pyimportmodulesosmaindir