Install psycopg2 on Ubuntu 18.04+

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