18

I can confirm psycopg2 is install (using conda install -c anaconda psycopg2) but the it seems psycopg2 cannot be imported to my python script or the interpreter is unable to locate it. I also tried installing using pip3, requirements are satisfied, meaning psycopg2 is already istalled, but cannot understand why I script isn't able to import it. Using Mac (OS v10.14.4)

$ python create_tables.py
Traceback (most recent call last):
  File "create_tables.py", line 1, in <module>
    import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

$ pip3 install psycopg2
Requirement already satisfied: psycopg2 in /usr/local/lib/python3.7/site-packages (2.8.2)
$ pip3 install psycopg2-binary
Requirement already satisfied: psycopg2-binary in /usr/local/lib/python3.7/site-packages (2.8.2)
python -V
Python 3.7.0

Any idea why this happen?

EDIT: create_table.py

import psycopg2
from config import config


def create_tables():
    """ create tables in the PostgreSQL database"""
    commands = (
        """
        CREATE TABLE vendors (
            vendor_id SERIAL PRIMARY KEY,
            vendor_name VARCHAR(255) NOT NULL
        )
        """,
        """ CREATE TABLE parts (
                part_id SERIAL PRIMARY KEY,
                part_name VARCHAR(255) NOT NULL
                )
        """,
        """
        CREATE TABLE part_drawings (
                part_id INTEGER PRIMARY KEY,
                file_extension VARCHAR(5) NOT NULL,
                drawing_data BYTEA NOT NULL,
                FOREIGN KEY (part_id)
                REFERENCES parts (part_id)
                ON UPDATE CASCADE ON DELETE CASCADE
        )
        """,
        """
        CREATE TABLE vendor_parts (
                vendor_id INTEGER NOT NULL,
                part_id INTEGER NOT NULL,
                PRIMARY KEY (vendor_id , part_id),
                FOREIGN KEY (vendor_id)
                    REFERENCES vendors (vendor_id)
                    ON UPDATE CASCADE ON DELETE CASCADE,
                FOREIGN KEY (part_id)
                    REFERENCES parts (part_id)
                    ON UPDATE CASCADE ON DELETE CASCADE
        )
        """)
    conn = None
    try:
        # read the connection parameters
        params = config()
        # connect to the PostgreSQL server
        conn = psycopg2.connect(**params)
        cur = conn.cursor()
        # create table one by one
        for command in commands:
            cur.execute(command)
        # close communication with the PostgreSQL database server
        cur.close()
        # commit the changes
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()


if __name__ == '__main__':
    create_tables()
4
  • Can you tell us more about what you are trying to accomplish with psycopg2? Pspcopg2 is the low-level database adapter used by ORMs; you rarely need to import it directly into your programs. In other words, it might be useful for us to see create_tables.py.
    – rriehle
    Apr 19, 2019 at 0:14
  • Question edited showing the content of create_table.py
    – arilwan
    Apr 19, 2019 at 0:25
  • Okay... good to see. I'm going to suggest you look into SqlAlchemy. Here is how to build a schema. It will save you from some of the lower level details.
    – rriehle
    Apr 19, 2019 at 0:36
  • Come to think of it, SqlAlchemy is not your only ORM option. There are many others: Peewee, PonyORM, SQLObject, Tortoise ORM. I have even seen Django's ORM used outside of Django. Any of these would save you some work over coding directly against psycopg2.
    – rriehle
    Apr 19, 2019 at 0:52

3 Answers 3

38

Yes, found a solution,

python -m pip install psycopg2-binary 

does the trick!

2
  • 2
    Great ,now you can either delete your question, or accept your own answer! Apr 19, 2019 at 1:13
  • 1
    Nice And Short, Thanks
    – Amir Jani
    Sep 14, 2020 at 20:31
3

Using Python3 the command is:

python3 -m pip install psycopg2-binary
3
  • 1
    the question stated Python version as 3.7.0, so the accepted answer should work with python3. I see not need for this.
    – user12587364
    Oct 10, 2021 at 15:38
  • If you are on Mac, pip or python refer to Python 2. You have to explicit specify the version, i.e., pip3 install ... or python3 -m pip install .... I can edit to make this answer more clear for other users Apr 2, 2022 at 3:01
  • @thenewjames unless you are NOT using virtualenv. Otherwise pip or python should work straight ahead referring to python 3.
    – user12587364
    Aug 15, 2022 at 12:29
0

I assume python points to python2, but you installed psycopg2 for python3 since you are using pip3. Install it via pip install pyscopg2 psycopg2-binary where pip should point to python2

9
  • pip install pyscopg2 psycopg2-binary Collecting pyscopg2 Could not find a version that satisfies the requirement pyscopg2 (from versions: ) No matching distribution found for pyscopg2
    – arilwan
    Apr 19, 2019 at 0:22
  • Yes, but I run alias python=python3 so as to use python3
    – arilwan
    Apr 19, 2019 at 0:29
  • Yes, sure, it does.
    – arilwan
    Apr 19, 2019 at 0:31
  • Just open up a prompt using python3, and try import psycopg2 there Apr 19, 2019 at 0:31
  • 1
    which simply points to the location of the executable file, pip and python are supposed to point to different ones, of course. This is another shot in the dark, but what if you try python -m pip install psycopg2? And then try to do import psycopg2 from the same interpreter.
    – VlB
    Apr 19, 2019 at 1:01

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.