Problems with module path in Python (ModuleNotFoundError: No module named)

Problems with module path in Python (ModuleNotFoundError: No module named)

今天 Python 中的模块出现问题。 我的文件结构:

- library
--- Storage.py
- scripts
--- run.py

和run.py代码:

import library.Storage as Storage

但我 运行 在 PyCharm 中它工作正常但是如果我 运行 在终端

python3 scripts/run.py

它return

    import library.Storage as Storage
ModuleNotFoundError: No module named 'library'

我试过这个

fpath = os.path.dirname(__file__)
sys.path.append(fpath)
print(sys.path)

['/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/opt/homebrew/lib/python3.9/site-packages', '/Users/binhot/PycharmProjects/MyProject/']

但问题依然存在

问题是 python 试图从 scripts 文件夹中导入模块 library。您需要做的是进行相对导入。在此处查看更多信息:https://realpython.com/absolute-vs-relative-python-imports/#relative-imports

我已经通过创建setup.sh将当前路径添加到 PYTHONPATH

解决了这个问题
export PYTHONPATH="${PYTHONPATH}:`pwd`"

现在可以正常使用了!