If you’re like me and you use Homebrew to install everything, you might have run into this error while doing pip3 install psycopg2
![](https://suryanshpradhan.wordpress.com/wp-content/uploads/2024/02/screenshot-2024-02-08-at-10.35.25e280afpm.png?w=2736)
Psycopg2 requires libpq and pg_config along with OpenSSL to install. While I could have also just installed it with psycopg2-binary
, I wanted to find out what was causing this issue.
I had libpq
installed by Homebrew in /opt/homebrew/Cellar/libpq/16.1_1/
and OpenSSL in /opt/homebrew/Cellar/openssl@3/3.2.1/
While installing psycopg2, you have to have pg_config
in your path. The setup.py in the source even provides a dedicated option for that. I was passing /opt/homebrew/Cellar/libpq/16.1_1/
in the $PATH variable while running pip3 install psycopg2
I tried using DYLD_LIBRARY_PATH
but that also didn’t work. I was not really in the mood to mess with setup.py and distutils since those were probably behind the generation of the actual compilation and linking commands. When I saw in the error above that Clang was using its -L
flag on the libpq directory to gain access to the library files. And it was also looking for libssl and libcrypto as seen with the -lssl
and -lcrypto
flags. I theorized that if I just symlinked (or simply just temporarily copied) the libssl and libcrypto libraries to the folder it would find those there because of the flags being passed to it.
So I did exactly that. To test it out, I even built everything from source. In the end I just copied the libcrypto* and libssl* files to /opt/homebrew/Cellar/
libpq/16.1_1/lib folder, assuming it would look up from the path where it found pg_config and look for a lib
folder in pg_config’s upper directory.
And it worked.
![](https://suryanshpradhan.wordpress.com/wp-content/uploads/2024/02/screenshot-2024-02-08-at-11.07.17e280afpm.png?w=2736)
![](https://suryanshpradhan.wordpress.com/wp-content/uploads/2024/02/screenshot-2024-02-08-at-11.06.46e280afpm.png?w=2736)
Then went back to the libpq lib
folder and deleted those files that I had just copied.
NOTE: This is obviously not the most ideal solution and I did this just for fun. It will work but it could mess up or break something else for you (example: programs/packages that depend on a specific version of OpenSSL, etc) so try it at your own risk. And make sure to remove whatever you put into the libpq lib
folder
Shell Script
#!/bin/bash
libraries=(ssl crypto)
for l in ${libraries[@]}; do
echo copying $i;
for i in $(find /opt/homebrew/opt/openssl\@3/lib -name "lib${l}*"); do
echo cp -v $i /opt/homebrew/opt/libpq/lib/;
cp -v $i /opt/homebrew/opt/libpq/lib/;
done;
done
echo "[press any key to delete when build is done]"
read
for i in ${libraries[@]}; do
echo removing /opt/homebrew/opt/libpq/lib/lib$i*
rm -vf /opt/homebrew/opt/libpq/lib/lib$i*
done