Skip to main content

How to Resolve "ModuleNotFoundError: No module named 'psycopg2'" in Python

The ModuleNotFoundError: No module named 'psycopg2' is a common Python error indicating that the interpreter can not find the psycopg2 library, which is the most popular PostgreSQL database adapter for Python. This usually means the necessary package hasn't been installed correctly in the active Python environment.

This guide provides clear steps to resolve this error, primarily by installing the recommended psycopg2-binary package.

Understanding the Error: Missing PostgreSQL Adapter

This error means that when Python executes import psycopg2, it searches its known locations for installed modules but can not find the psycopg2 library.

For most users, the easiest and recommended way to install psycopg2 is by installing the psycopg2-binary package. This package includes pre-compiled binaries, avoiding the need for C compilers or external PostgreSQL development libraries on your system.

Open your terminal or command prompt and run:

pip install psycopg2-binary

Variations (Choose the one appropriate for your setup):

# If you primarily use Python 3
pip3 install psycopg2-binary

# If pip/pip3 are not in your system PATH
python -m pip install psycopg2-binary
python3 -m pip install psycopg2-binary

# On Windows, 'py' launcher might be available
py -m pip install psycopg2-binary

Alternative: Installing psycopg2 (Requires Build Tools)

You can install the source distribution package named psycopg2 directly (pip install psycopg2). However, this requires:

  • A C compiler installed on your system.
  • The PostgreSQL development headers and libraries (libpq-dev on Debian/Ubuntu, postgresql-devel on Fedora/CentOS/RHEL, or installing PostgreSQL via brew on macOS).

Unless you have a specific reason to build from source (e.g., needing specific compilation flags), using psycopg2-binary is much simpler.

  • macOS (using Homebrew):
    brew install postgresql
    pip install psycopg2 # Now pip can build from source
  • Debian/Ubuntu:
    sudo apt update
    sudo apt install build-essential libpq-dev python3-dev
    pip3 install psycopg2
  • Fedora/CentOS/RHEL:
    sudo yum install python3-devel postgresql-devel # Or dnf for newer Fedora
    pip3 install psycopg2

Troubleshooting Common Installation Problems:

If installing psycopg2-binary (or psycopg2) fails or the ModuleNotFoundError persists, check these points:

  • Using the Correct pip: Ensure you're using pip3 or python3 -m pip for your Python 3 environment.
  • Working with Virtual Environments (Crucial!): This is the most common issue. Make sure your virtual environment is activated before running pip install. Also, ensure your IDE is using the interpreter from that virtual environment.
    # Activate your environment first!
    # e.g., source venv/bin/activate (Linux/macOS)
    pip install psycopg2-binary
  • Permissions Issues (--user or sudo): If installing globally (not recommended).
    • Try: pip install psycopg2-binary --user
    • Use sudo cautiously (Linux/macOS): sudo pip install psycopg2-binary
  • Multiple Python Installations / IDE Configuration: Verify your IDE (VS Code, PyCharm) is using the same Python interpreter where you installed the package. Use the "Select Interpreter" feature in your IDE.
  • Naming Conflicts (psycopg2.py): Do not name your own Python files psycopg2.py. Rename your file if there's a conflict. Avoid using psycopg2 as a variable name before importing.

Verifying Installation (pip show)

Check if the package was installed correctly in the active environment:

pip show psycopg2-binary
# Or: pip3 show psycopg2-binary

This command should display package details if successful.

Platform/Tool Specific Installation Notes:

  • Windows: Use CMD or PowerShell. py -m pip install psycopg2-binary is often reliable. Run as Administrator for global installs if needed (prefer venvs or --user).
  • macOS / Linux: Use the Terminal. Use pip3 or python3 -m pip. Use sudo cautiously for global installs.
  • VS Code: Use the integrated terminal (Ctrl + `` ). Ensure the correct Python interpreter (usually from a venv) is selected.
  • PyCharm: Use the Terminal (Alt+F12) or the Python Packages tool. Ensure the correct project interpreter is selected.
  • Anaconda: Use the Anaconda Prompt or terminal in an active conda environment.
    conda install -c conda-forge psycopg2 # Conda often manages dependencies better
    # Or use pip within conda:
    pip install psycopg2-binary
  • Jupyter Notebook: Install from a notebook cell:
    !pip install psycopg2-binary
    # Or: !pip install psycopg2-binary --user
    Restart the kernel after installation.

Using psycopg2 After Installation

Regardless of whether you installed psycopg2-binary or psycopg2, you import it as psycopg2 in your Python code:

import psycopg2
import os # Example for getting connection details

try:
# Replace with your actual database connection details
# Consider using environment variables for security
conn = psycopg2.connect(
dbname=os.environ.get("DB_NAME", "test"),
user=os.environ.get("DB_USER", "postgres"),
password=os.environ.get("DB_PASSWORD", ""),
host=os.environ.get("DB_HOST", "localhost"),
port=os.environ.get("DB_PORT", "5432")
)

cur = conn.cursor()
print("Successfully connected to database.")

# Example query
cur.execute("SELECT version();")
db_version = cur.fetchone()
print(f"PostgreSQL version: {db_version[0]}")

# Remember to close cursor and connection
cur.close()
conn.close()

except ImportError:
print("Error: psycopg2 module not found.")
print("Please install it using: pip install psycopg2-binary")
except psycopg2.OperationalError as e:
print(f"Unable to connect to the database: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

Conclusion

The ModuleNotFoundError: No module named 'psycopg2' usually indicates that the required PostgreSQL adapter package is not installed in your current Python environment.

  • The recommended solution for most users is to install the psycopg2-binary package using pip.
  • Ensure you are working within the correct virtual environment and using the appropriate pip command for your setup.
  • If you specifically need to build from source, install psycopg2 after ensuring the necessary build dependencies are present on your system.