How to Resolve "ModuleNotFoundError: No module named psycopg2" in Python
Fix the ModuleNotFoundError for psycopg2 in Python by installing the correct package (psycopg2-binary) or resolving environment and dependency issues.
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.
Solution 1: Install psycopg2-binary using pip (Recommended)
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):
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 postgresqlpip install psycopg2 # Now pip can build from source
sudo yum install python3-devel postgresql-devel # Or dnf for newer Fedorapip3 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.
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
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.
Regardless of whether you installed psycopg2-binary or psycopg2, you import it as psycopg2 in your Python code:
import psycopg2import os # Example for getting connection detailstry: 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.") cur.execute("SELECT version();") db_version = cur.fetchone() print(f"PostgreSQL version: {db_version[0]}") 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.