Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't import work when running the script from the console?

In the file create_admin_user.py I write: from models import User, Role, Session
At startup create_admin_user.py everything is fine from PyCharm, but when I run it from the terminal with the command python create_admin_user.py returns error: ModuleNotFoundError: No module named 'models'
Here is my models.__init__.py:

from .base import Base, engine, Session
from .doctor importDoctor
from .specialization import Specialization
from .address import Address
from .user import User
from .file import Role

Base.metadata.create_all(engine)

Project structure:

src/
  models/
    __init__.py
  scripts/
    create_admin_user.py

What is the reason and how to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried writing from ..models import User, Role, Session didn’t help

>Solution :

You need to add the src directory to your module search path by modifying the PYTHONPATH environment variable or by directly modifying sys.path.
Try running python -m site before running your script to inspect the contents of sys.path.

Here is an example:

$ python3 -m site
sys.path = [
    '/home/users/Никита',
    '/usr/lib64/python39.zip',
    '/usr/lib64/python3.9',
    '/usr/lib64/python3.9/lib-dynload',
    '/usr/lib64/python3.9/site-packages',
    '/usr/lib/python3.9/site-packages',
]
USER_BASE: '/home/users/Никита/.local' (exists)
USER_SITE: '/home/users/Никита/.local/lib/python3.9/site-packages' (doesn't exist)
ENABLE_USER_SITE: True

$ PYTHONPATH='/home/users/Никита/projects/YourProject/src' python3 -m site
sys.path = [
    '/home/users/Никита',
    '/home/users/Никита/projects/YourProject/src',
    '/usr/lib64/python39.zip',
    '/usr/lib64/python3.9',
    '/usr/lib64/python3.9/lib-dynload',
    '/usr/lib64/python3.9/site-packages',
    '/usr/lib/python3.9/site-packages',
]
USER_BASE: '/home/users/Никита/.local' (exists)
USER_SITE: '/home/users/Никита/.local/lib/python3.9/site-packages' (doesn't exist)
ENABLE_USER_SITE: True

$ PYTHONPATH='/home/users/Никита/projects/YourProject/src' python create_admin_user.py

Here is a link to the official Python documentation that discusses the initialization of the module search path: https://docs.python.org/3/library/sys_path_init.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading