Install psycopg2 on Ubuntu 18.04+

I was trying to install psycopg2 database adapter for PostgreSQL on Ubuntu 18.04. And was always getting an error when doing “pipenv install psycopg2”, complaining about “Python.h” missing.

After much head-scratching, I found the issue. Multiple Python distributions confuse psycopg2 installation.

Its like this. psycopg2 has two main dependencies libpq-dev python3-dev.

On Ubuntu, you install them like this:
sudo apt-get install libpq-dev python3-dev

The issue here is that python3-dev is very misleading if you have multiple Python3 versions installed.

For reasons outside of the context of this post, I have Python2.7 (default), Python3.6, Python3.7 and Python3.8 on my machine.

All of my recent work is done in pipenv based virtualenvs and they are either Python3.7 or Python3.8.

So, coming to the issue. python3-dev points to Python3.6. My virtualenvs were either Python3.7 or Python3.8. So, obviously this step: pipenv install psycopg2 would fail, with something on lines of Python.h not found.

So, the fix is:

Python 3.7

sudo apt-get update
sudo apt-get install libpq-dev python3.7-dev
pipenv install --python=3.7 psycopg2
pipenv shell

Python 3.8

sudo apt-get update
sudo apt-get install libpq-dev python3.8-dev
pipenv install --python=3.8 psycopg2
pipenv shell

Tek Shinobi
Author: Tek Shinobi

Hiya Ninjas, I am the ninja who invented the fire, wheel, science, technology and everything intelligent this humanity has ever experienced since its evolution from monkeys and germs. Actually, above is a partial list. I also was involved with the Big Bang that created this universe. What was it like before the Big Bang is so secret that if I tell you, I will have to turn you into a hobbit and force you to be my gardener. Okay. Sayonanra, Namaste Tek Shinobi




2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *