W3docs

pg_config executable not found

Check the location of pg_config: Open a terminal and run the command "which pg_config".

  1. Check the location of pg_config: Open a terminal and run the command which pg_config. This will show you the location of the pg_config executable on your system.
  2. Add the directory containing pg_config to your PATH environment variable: If the pg_config executable is not in one of the directories listed in your PATH environment variable, you will need to add it. You can do this by adding the following line to your .bashrc or .bash_profile file: export PATH=$PATH:/path/to/directory/containing/pg_config
  3. Install PostgreSQL development headers: If you are unable to locate the pg_config executable, you may need to install the PostgreSQL development libraries. These are required for building the psycopg2 library. Use your system's package manager:
    • Ubuntu/Debian: sudo apt install libpq-dev python3-dev
    • CentOS/RHEL/Fedora: sudo dnf install postgresql-devel python3-devel
    • macOS (Homebrew): brew install postgresql
  4. Install the psycopg2 package using pip: After resolving the pg_config issue, you can install the package. For most environments, it is recommended to use the pre-compiled binary to bypass compilation and avoid the pg_config error entirely: pip install psycopg2-binary. Alternatively, run pip install psycopg2.
  5. Verify that the installation was successful: To verify that the psycopg2 package was installed correctly, you can run the command pip show psycopg2 in your terminal. This will show you information about the package, including the version number and location.
  6. Test the connection to the PostgreSQL database: To test the connection to the PostgreSQL database, you can use the following Python code snippet.

Test the PostgreSQL connection in Python

import psycopg2

try:
    with psycopg2.connect(
        host="hostname",
        database="dbname",
        user="username",
        password="password"
    ) as conn:
        print("Connection established.")
except psycopg2.Error as e:
    print(f"Unable to connect to the database: {e}")

If the connection is established successfully, you will see the message "Connection established.". If not, you should see the error message indicating the connection failure.