How to install psycopg2 with pg_config error?

Debian/Ubuntu

Python 2

sudo apt install libpq-dev python-dev

Python 3

sudo apt install libpq-dev python3-dev

Additional

If none of the above solve your issue, try

sudo apt install build-essential
or

sudo apt install postgresql-server-dev-all

With pip

Install the psycopg2-binary PyPI package instead, it has Python wheels for Linux and Mac OS.

pip install psycopg2-binary

If you need to install without compiling:

pip install psycopg2-binary

https://www.psycopg.org/docs/install.html#binary-install-from-pypi

Note: The psycopg2-binary package is meant for beginners to start playing with Python and PostgreSQL without the need to meet the build requirements. If you are the maintainer of a publish package depending on psycopg2 you shouldn’t use ‘psycopg2-binary’ as a module dependency. For production use you are advised to use the source distribution.


I was getting this issue because I hadn't yet installed PostgreSQL on my machine.

For Mac

brew install postgresql

For Mac without brew

python3 -m pip install psycopg2-binary