Search code examples
python-3.xpostgresqlsqlalchemy

(No module named sqlalchemy) but why since I have it installed


I am trying to run a simple python3 code that creates a Postgressql table

import os

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")

engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))

def main():
    db.execute("CREATE TABLE books (id SERIAL PRIMARY KEY, isbn INTEGER UNIQUE, title VARCHAR NOT NULL, auther VARCHAR NOT NULL, year INTEGER NOT NULL")
    db.commit()

if __name__ == "__main__":
    main()

I set the DATABASE_URL

However when I run it on my terminal (macOS Catalina) I get this message:

Traceback (most recent call last):
  File "create.py", line 3, in <module>
    from sqlalchemy import create_engine
ImportError: No module named sqlalchemy

So I tried to install sqlalchemy and it already has been installed.

% pip3 install sqlalchemy
Requirement already satisfied: sqlalchemy in /usr/local/lib/python3.7/site-packages (1.3.17) 

Solution

  • There is likely a system version of Python 3 for which SQLAlchemy was installed using the prior command.

    You can ensure the module will be installed for the specific version of Python 3 you're using with:

    $ python3.7 -m pip install -U sqlalchemy
    

    -m is telling python3.7 to run the pip module as a script, and -U is there to upgrade SQLAlchemy if a newer version is found -- not an issue in this particular case, but a good habit to be in.