0

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/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/']

but the problems still happen

mzjn
  • 48,958
  • 13
  • 128
  • 248
Bình Ông
  • 96
  • 7
  • 1
    Welcome to Stack Overflow. Did you add a ```__init__.py``` to your ```library``` directory? – ewokx May 26 '22 at 05:39
  • Already add __init__.py in library – Bình Ông May 26 '22 at 06:12
  • You can 1) move run.py to the directory above "scripts" **or** 2) run the script as a module like this: `python3 -m scripts.run`. See https://stackoverflow.com/a/14132912/407651. – mzjn May 26 '22 at 10:33

2 Answers2

2

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

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

now it work fine !

Bình Ông
  • 96
  • 7
1

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

Michael M.
  • 10,486
  • 9
  • 18
  • 34