Reputation: 96
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
Upvotes: 0
Views: 3029
Reputation: 96
I had solve this problems by create setup.sh
to add current path to PYTHONPATH
export PYTHONPATH="${PYTHONPATH}:`pwd`"
now it work fine !
Upvotes: 2
Reputation: 11080
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
Upvotes: 1