Installing psycopg2 on MacOS
213 words, 1 minute

The python psycopg2 library for Postgres has a dependency on an ssl library, which on modern MacOS versions, (Sierra onwards) can cause installation issues for various reasons, but usually stemming from the openssl versions that ship by default with MacOS.

The command below installs with poetry add, which can be replaced with pip install if you’re using pip.

The error you may see when installing psycopg2 is pretty self-explanatory - library not found for -lssl:

$ poetry add psycopg2
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'clang' failed with exit status 1
----------------------------------------

The solution is to install openssl with brew, and then manually provide the directory to the linker with the LDFLAGS option when installing. The directory is the default installation directory for brew, like so:

$ env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" poetry add psycopg2

The full output will look something like this:

$ brew install openssl
==> Installing [email protected]
==> Downloading https://homebrew.bintray.com/bottles/[email protected]
==> Pouring [email protected]
==> Summary
🍺  /usr/local/Cellar/[email protected]/1.1.1g: 8,059 files, 18MB
$ env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" poetry add psycopg2
Using version ^2.8.5 for psycopg2
Updating dependencies
Resolving dependencies... (0.1s)
Package operations: 2 installs, 0 updates, 0 removals
  - Installing psycopg2 (2.8.5)
  - Installing pytest (5.4.1)
Done!
$ _