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

Time:05-27

Today I have a problem with module in Python. My file structure:

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

and run.py code:

import library.Storage as Storage

but I run this in PyCharm it work fine but if I run in terminal

python3 scripts/run.py

it return

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

I had tried this

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

['/opt/homebrew/Cellar/[email protected]/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/opt/homebrew/Cellar/[email protected]/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/opt/homebrew/Cellar/[email protected]/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/']

but the problems still happen

CodePudding user response:

The problem is that python is trying to import the module library from inside the scripts folder. What you need to do is make a relative import. See more here: https://realpython.com/absolute-vs-relative-python-imports/#relative-imports

CodePudding user response:

I had solve this problems by create setup.shto add current path to PYTHONPATH

export PYTHONPATH="${PYTHONPATH}:`pwd`"

now it work fine !

CodePudding user response:

Add an __init__.py file to the library directory.

  • Related