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()
arilwan
  • 3,374
  • 5
  • 26
  • 62
  • 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 '19 at 00:14
  • Question edited showing the content of `create_table.py` – arilwan Apr 19 '19 at 00:25
  • Okay... good to see. I'm going to suggest you look into [SqlAlchemy](https://www.sqlalchemy.org). [Here is how to build a schema](https://docs.sqlalchemy.org/en/13/orm/tutorial.html#create-a-schema). It will save you from some of the lower level details. – rriehle Apr 19 '19 at 00: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 '19 at 00:52

3 Answers3

38

Yes, found a solution,

python -m pip install psycopg2-binary 

does the trick!

arilwan
  • 3,374
  • 5
  • 26
  • 62
3

Using Python3 the command is:

python3 -m pip install psycopg2-binary
me72921
  • 173
  • 2
  • 10
  • 1
    the question stated Python version as `3.7.0`, so the accepted answer should work with python3. I see not need for this. –  Oct 10 '21 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 – thenewjames Apr 02 '22 at 03:01
  • @thenewjames unless you are NOT using `virtualenv`. Otherwise `pip` or `python` should work straight ahead referring to `python 3`. –  Aug 15 '22 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

Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • `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 '19 at 00:22
  • Yes, but I run `alias python=python3` so as to use python3 – arilwan Apr 19 '19 at 00:29
  • Yes, sure, it does. – arilwan Apr 19 '19 at 00:31
  • Just open up a prompt using python3, and try `import psycopg2` there – Devesh Kumar Singh Apr 19 '19 at 00:31
  • I tried doing import from python interpreter, yet module can't be found ```$ python3 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import psycopg2 Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'psycopg2'``` – arilwan Apr 19 '19 at 00:34
  • What does `which python3.7` gives you? – Devesh Kumar Singh Apr 19 '19 at 00:36
  • `which python3.7 /usr/local/bin/python3.7` – arilwan Apr 19 '19 at 00:37
  • Could this be the isssue? `which pip3 /usr/local/bin/pip3` compared to `which python3.7 /usr/local/bin/python3.7` – arilwan Apr 19 '19 at 00:49
  • 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 '19 at 01:01