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/[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

3
  • 1
    Welcome to Stack Overflow. Did you add a __init__.py to your library directory? Commented May 26, 2022 at 5:39
  • Already add init.py in library Commented May 26, 2022 at 6: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 stackoverflow.com/a/14132912/407651. Commented May 26, 2022 at 10:33

2 Answers 2

2

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

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

now it work fine !

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

I had tried this also but still ImportError: attempted relative import with no known parent package
The parent directory of your library and script directories must also be a package with a __init__.py file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.