Search code examples
pythonpycharmpython-import

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?

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