Modulenotfounderror no module named psycopg2 windows

A common error you may encounter when using Python is modulenotfounderror: no module named ‘psycopg2’.

This error occurs when the Python interpreter cannot detect the Psycopg library in your current environment.

You can install Psycopg2 in Python 3 with python3 -m pip install psycopg2-binary.

This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.


Table of contents

  • ModuleNotFoundError: no module named ‘psycopg2’
    • What is ModuleNotFoundError?
    • What is Psycopg2?
  • Always Use a Virtual Environment to Install Packages
    • How to Install Psycopg2 on Windows Operating System
      • Psycopg2 installation on Windows Using pip
    • How to Install Psycopg2 on Mac Operating System using pip
    • How to Install Psycopg2 on Linux Operating Systems
      • Installing pip for Ubuntu, Debian, and Linux Mint
      • Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
      • Installing pip for CentOS 6 and 7, and older versions of Red Hat
      • Installing pip for Arch Linux and Manjaro
      • Installing pip for OpenSUSE
      • Psycopg2 installation on Linux with Pip
  • Installing Psycopg2 Using Anaconda
    • Check Psycopg2 Version
  • Summary

ModuleNotFoundError: no module named ‘psycopg2’

What is ModuleNotFoundError?

The ModuleNotFoundError occurs when the module you want to use is not present in your Python environment. There are several causes of the modulenotfounderror:

The module’s name is incorrect, in which case you have to check the name of the module you tried to import. Let’s try to import the re module with a double e to see what happens:

import ree
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
1 import ree

ModuleNotFoundError: No module named 'ree'

To solve this error, ensure the module name is correct. Let’s look at the revised code:

import re

print(re.__version__)
2.2.1

You may want to import a local module file, but the module is not in the same directory. Let’s look at an example package with a script and a local module to import. Let’s look at the following steps to perform from your terminal:

mkdir example_package

cd example_package

mkdir folder_1

cd folder_1

vi module.py

Note that we use Vim to create the module.py file in this example. You can use your preferred file editor, such as Emacs or Atom. In module.py, we will import the re module and define a simple function that prints the re version:

import re

def print_re_version():

    print(re.__version__)

Close the module.py, then complete the following commands from your terminal:

cd ../

vi script.py

Inside script.py, we will try to import the module we created.

import module

if __name__ == '__main__':

    mod.print_re_version()

Let’s run python script.py from the terminal to see what happens:

Traceback (most recent call last):
  File "script.py", line 1, in ≺module≻
    import module
ModuleNotFoundError: No module named 'module'

To solve this error, we need to point to the correct path to module.py, which is inside folder_1. Let’s look at the revised code:

import folder_1.module as mod

if __name__ == '__main__':

    mod.print_re_version()

When we run python script.py, we will get the following result:

2.2.1

Lastly, you can encounter the modulenotfounderror when you import a module that is not installed in your Python environment.

What is Psycopg2?

Psycopg2 is a PostgreSQL database adapter for Python. It provides an API to connect to an external database.

The simplest way to install psycopg2 is to use the package manager for Python called pip. The following installation instructions are for the major Python version 3.

Always Use a Virtual Environment to Install Packages

It is always best to install new libraries within a virtual environment. You should not install anything into your global Python interpreter when you develop locally. You may introduce incompatibilities between packages, or you may break your system if you install an incompatible version of a library that your operating system needs. Using a virtual environment helps compartmentalize your projects and their dependencies. Each project will have its environment with everything the code needs to run. Most ImportErrors and ModuleNotFoundErrors occur due to installing a library for one interpreter and trying to use the library with another interpreter. Using a virtual environment avoids this. In Python, you can use virtual environments and conda environments. We will go through how to install psycopg2 with both.

How to Install Psycopg2 on Windows Operating System

First, you need to download and install Python on your PC. Ensure you select the install launcher for all users and Add Python to PATH checkboxes. The latter ensures the interpreter is in the execution path. Pip is automatically on Windows for Python versions 2.7.9+ and 3.4+.

You can check your Python version with the following command:

python3 --version

You can install pip on Windows by downloading the installation package, opening the command line and launching the installer. You can install pip via the CMD prompt by running the following command.

python get-pip.py

You may need to run the command prompt as administrator. Check whether the installation has been successful by typing.

pip --version

Psycopg2 installation on Windows Using pip

To install psycopg2, first create the virtual environment. The environment can be any name, in this we choose “env”:

virtualenv env

You can activate the environment by typing the command:

env\Scripts\activate

You will see “env” in parenthesis next to the command line prompt. You can install psycopg2 within the environment by running the following command from the command prompt.

python3 -m pip install psycopg2-binary

We use python -m pip to execute pip using the Python interpreter we specify as Python. Doing this helps avoid ImportError when we try to use a package installed with one version of Python interpreter with a different version. You can use the command which python to determine which Python interpreter you are using.

How to Install Psycopg2 on Mac Operating System using pip

Open a terminal by pressing command (⌘) + Space Bar to open the Spotlight search. Type in terminal and press enter. To get pip, first ensure you have installed Python3:

python3 --version
Python 3.8.8

Download pip by running the following curl command:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

The curl command allows you to specify a direct download link. Using the -o option sets the name of the downloaded file.

Install pip by running:

python3 get-pip.py

To install psycopg2, first create the virtual environment:

python3 -m venv env

Then activate the environment using:

source env/bin/activate 

You will see “env” in parenthesis next to the command line prompt. You can install psycopg2 within the environment by running the following command from the command prompt.

python3 -m pip install psycopg2-binary

How to Install Psycopg2 on Linux Operating Systems

All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip. Open a terminal and use the commands relevant to your Linux distribution to install pip.

Installing pip for Ubuntu, Debian, and Linux Mint

sudo apt install python-pip3

Installing pip for CentOS 8 (and newer), Fedora, and Red Hat

sudo dnf install python-pip3

Installing pip for CentOS 6 and 7, and older versions of Red Hat

sudo yum install epel-release

sudo yum install python-pip3

Installing pip for Arch Linux and Manjaro

sudo pacman -S python-pip

Installing pip for OpenSUSE

sudo zypper python3-pip

Psycopg2 installation on Linux with Pip

To install psycopg2, first create the virtual environment:

python3 -m venv env

Then activate the environment using:

source env/bin/activate 

You will see “env” in parenthesis next to the command line prompt. You can install psycopg2 within the environment by running the following command from the command prompt.

Once you have activated your virtual environment, you can install psycopg2 using:

python3 -m pip install psycopg2-binary

Installing Psycopg2 Using Anaconda

Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have installed Anaconda, you can create a virtual environment and install psycopg2.

To create a conda environment you can use the following command:

conda create -n psycopg2 python=3.8

You can specify a different Python 3 version if you like. Ideally, choose the latest version of Python. Next, you will activate the project container. You will see “psycopg2” in parentheses next to the command line prompt.

source activate psycopg2

Now you’re ready to install psycopg2 using conda.

Once you have activated your conda environment, you can install psycopg2 using the following command:

conda install -c anaconda psycopg2

Check Psycopg2 Version

Once you have successfully installed psycopg2, you can check its version. If you used pip to install psycopg2, you can use pip show from your terminal.

python3 -m pip show psycopg2-binary
Name: psycopg2-binary
Version: 2.9.3
Summary: psycopg2 - Python-PostgreSQL Database Adapter

Second, within your python program, you can import psycopg2 and then reference the __version__ attribute:

import psycopg2
print(psycopg2.__version__)
2.9.3

If you used conda to install psycopg2, you could check the version using the following command:

conda list -f psycopg2
# Name                    Version                   Build  Channel
psycopg2                  2.8.5            py38hddc9c9b_0    anaconda

Summary

Congratulations on reading to the end of this tutorial. The modulenotfounderror occurs if you misspell the module name, incorrectly point to the module path or do not have the module installed in your Python environment. If you do not have the module installed in your Python environment, you can use pip to install the package. However, you must ensure you have pip installed on your system. You can also install Anaconda on your system and use the conda install command to install psycopg2.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

For further reading on missing modules in Python, go to the article:

  • How to Solve Python ModuleNotFoundError: no module named ‘urllib2’.
  • How to Solve ModuleNotFoundError: no module named ‘plotly’.
  • How to Solve Python ModuleNotFoundError: no module named ‘boto3’.

Have fun and happy researching!

The modulenotfounderror no module named ‘psycopg2’ Windows code exception usually affects your programming experience when the system cannot find the adequate library. As a result, it launches a module named error log, halting further procedures, affecting your Jupyter Notebook project, and terminating the program.Modulenotfounderror No Module Named PSYCOPG2

In addition, we confirmed the modulenotfounderror: no module named ‘psycopg2’ Mac mistake when forgetting to install psycopg, which is atypical with advanced projects and applications.

Therefore, we wrote the most sophisticated module named psycopg debugging guide, using real-life examples and techniques, so dive into this guide to overcome the modulenotfounderror: no module named ‘psycopg2’ Docker issue.

Contents

  • Why Is the Modulenotfounderror No Module Named PSYCOPG2 Bug Happening?
    • – Running a Flexible Server With an Inadequate Library
    • – Installing the Psycopg Package With Pip Commands
  • How to Fix the Modulenotfounderror No Module Named PSYCOPG2 Error?
    • – Importing the Binary and Psycopg Packages
  • Conclusion

Why Is the Modulenotfounderror No Module Named PSYCOPG2 Bug Happening?

The modulenotfounderror: no module named ‘psycopg2’ Python3 bug is happening because the machine cannot find the named psycopg library. However, programmers experienced a similar error log when forgetting to install the necessary file or command for the Jupyter Notebook project, affecting several processes and procedures in the main document.

For example, this broken exception is inevitable when using the pip install property with invalid inputs and values. As a result, the application confirms the modulenotfounderror no module named ‘psycopg2’ SQLalchemy bug and halts further procedures, although some code snippets and commands raise no warnings.

However, the program’s invalid message indicates where the process fails, which is critical when applying the solutions and debugging techniques, although it differs for all operating systems. Henceforth, this guide teaches you how to reproduce and exemplify the broken syntax before implementing the solutions to prevent further complications and unexpected warnings, such as the modulenotfounderror: no module named ‘psycopg2’ Django.

Furthermore, you will likely experience the same code exception when you forget to provide the psycopg binary module in the primary file. The modulenotfounderror: no module named ‘psycopg2’ odoo bug happens before importing the flawed module or installing it in an unrecognized environment.

Although these instances are uncommon with complex projects and programs, the bug can occur when you expect the least and can sometimes affect other elements and functions. As a result, let us reproduce the modulenotfounderror no module named ‘psycopg2’ Jupyter Notebook error, troubleshoot the program, and locate the failed commands before altering their values and fixing the message.

– Running a Flexible Server With an Inadequate Library

Incorrect libraries and settings can obliterate flexible servers and locations, as this section confirms. Hence, we will exemplify what happens to your program after running the server with inadequate libraries. First, however, we will provide the environment to teach you more about the versions and extensions.Modulenotfounderror No Module Named PSYCOPG2 Causes

You can learn more about the machine’s environment below:

Windows 10 – 10.0.22000 – SP0

Python 3.10.3

Installer: MSI

azure-cli 2.35.0

Extensions:

azure-dev 0.0.1b456

containerapp 0.1.3

rdbms-connect 1.0.1

Dependencies:

msal 1.17.0

azure-mgmt-resource 20.0.0

These versions appear functional and error-free, but the warning confirms the failed procedures. The following example provides the complete stack trace after running the flexible server:

The command failed with an unexpected error. Here is the traceback:

No module named ‘psycopg2._psycopg’

Traceback (most recent call last):

File “D: \a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\knack/cli.py”, line 222, in invoke

File “D: \a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py”, line 583, in execute

File “D: \a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\knack/parser.py”, line 261, in parse_args

File “argparse.py”, line 1825, in parse_args

File “D: \a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/parser.py”, line 284, in parse_known_args

File “argparse.py”, line 1858, in parse_known_args

File “argparse.py”, line 2049, in _parse_known_args

File “argparse.py”, line 2026, in consume_positionals

File “argparse.py”, line 1935, in take_action

File “argparse.py”, line 1213, in __call__

File “D: \a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/parser.py”, line 284, in parse_known_args

File “argparse.py”, line 1858, in parse_known_args

File “argparse.py”, line 2049, in _parse_known_args

File “argparse.py”, line 2026, in consume_positionals

File “argparse.py”, line 1935, in take_action

File “argparse.py”, line 1213, in __call__

File “argparse.py”, line 1858, in parse_known_args

File “argparse.py”, line 2067, in _parse_known_args

File “argparse.py”, line 2007, in consume_optional

File “argparse.py”, line 1935, in take_action

File “argparse.py”, line 1098, in __call__

File “argparse.py”, line 2555, in print_help

As you can tell, this error log indicates the failed paths, locations, and libraries ruining your programming experience. Still, you can encounter similar warnings when messing with the pip commands.

– Installing the Psycopg Package With Pip Commands

When installing the psycopg package with pip commands, your system will likely raise a warning. Although this procedure sounds straightforward because the system needs a few command lines, the version does not support the configurations and fails to execute the functions.

Due to this reason, we will provide the entire visual output confirming and indicating the flawed processes. However, this information is beneficial when repairing the pip commands.

The following example provides the flawed pip command:

(.venv) > pip install psycopg2 == 2.8.5

Collecting psycopg2 == 2.8.5

Using cached psycopg2 – 2.8.5.tar.gz (355 kB)

ERROR: Command flawed out with exit status 1:

command: ‘D:\ git\ .venv\ Scripts\ python.exe’ -c ‘import io, os, sys, setuptool, token; sys.argv [0] = ‘”‘”‘C:\\ Users\\ AppData\\ Local\\ Temp\\ pip-install-_ui_ttte\\ psycopg2_280\\ setup.py’”‘”‘; __file__ = ‘”‘”‘C:\\ Users\\ AppData\\ Local\\ Temp\\ pip-install-_ui_ttte\\ psycopg2_2b3\\setup.py’”‘”‘;f = getatt (token, ‘”‘”‘open’”‘”‘, opens) (__file__) if os.path.exist (__file__) else io.StringsIO (‘”‘”‘from setuptools import setup; setup ()’”‘”‘); codes = f.read().replaces (‘”‘”‘\r\n’”‘”‘, ‘”‘”‘\n’”‘”‘); f.close();exec (compiles (code, __file__, ‘”‘”‘exec’”‘”‘))’ egg_info –egg-base ‘C:\Users\AppData\Local\Temp\pip-pip-egg-info-908mx2tm’

cwd: C:\Users\AppData\Local\Temp\pip-install-_ui_ttte\psycopg2_2b37\

Complete output (23 lines):

running egg_info

creating C:\Users\AppData\Local\Temp\pip-pip-egg-info-908mx2tm\psycopg2.egg-info

writing C:\Users\AppData\Local\Temp\pip-pip-egg-info-908mx2tm\psycopg2.egg-info\PKG-INFO

writing dependency_links to C:\Users\AppData\Local\Temp\pip-pip-egg-info-908mx2tm\psycopg2.egg-info\dependency_links.txt

writing top-level names to C:\Users\AppData\Local\Temp\pip-pip-egg-info-908mx2tm\psycopg2.egg-info\top_level.txt

writing manifest file ‘C:\Users\AppData\Local\Temp\pip-pip-egg-info-908mx2tm\psycopg2.egg-info\SOURCE.txt’

Error: pg_config not found.

pg_config is needed to build psycopg2 from source. Please add it to the directory

containing pg_config to $PATH or specify the complete executable path with the

option:

python setup.py build_ext –pg-config /path/to/pg_config builds …

or with pg_config options in ‘setup.cfg’.

If you wish to avoid building psycopg2 from source, install the PyPI

‘psycopg2-binary’ package instead.

For other information check the ‘doc/src/install.rst’ file (also at

<https://www.psycopg.org/docs/install.html>)

We kept the example as short as possible to capture its effect on your program. Nevertheless, the debugging techniques apply to all systems and programs.

How to Fix the Modulenotfounderror No Module Named PSYCOPG2 Error?

You can fix the modulenotfound no module named psycopg2 error by installing the adequate module for the main commands. As a result, you will provide the paths and locations, reenabling the failed libraries. In addition to that, you can repair the program by importing the binary packages.



Although many reasons and causes display the same mistake, a single debugging technique resolves all inconsistencies. Therefore, this chapter teaches you how to repair the program by installing the missing module for the leading functions. In addition, we suggest updating your Python program if you use versions older than 2.7.

Learn more about the debugging technique in the following code snippet:

# Python 2.7.6:

$ wget http://python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz

$ tar xf Python-2.7.6.tar.xz

$ cd Python-2.7.6

$ ./configure –prefix=/usr/local –enable-unicode=ucs4 –enable-shared LDFLAGS=”-Wl,-rpath /usr/local/lib”

$ make && make altinstall

$ yum install postgresql-libs

# First get the setup script for Setuptools:

$ wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py

# Then install it for Python 2.7 and/or Python 3.3:

$ python2.7 ez_setup.py

$ easy_install-2.7 psycopg2

We can confirm the system installed the psycopg module or package by looking at the visual output. In addition, the output indicates the location and number of files.

The following example confirms the successful installation:

C:\Users\Desktop\Py Practice>pip install psycopg2

Collecting psycopg2

Downloading https://files.pythonhosted.org/ packages/ 79/ ad/ 327e9c1e09/ psycopg2 – 2.8.4 – cp38 – cp38 – win32.whl (986kB)

| | 1551kB 133kB/s

Installing collected packages: psycopg2

Successfully installed psycopg2 – 2.8.4

Your program should no longer encounter this warning regardless of the other commands’ functionalities and inputs. However, importing the same package or module is another advanced debugging approach you can use.

– Importing the Binary and Psycopg Packages

The solution sometimes requires importing the binary and psycopg packages to render the values. Therefore, as the former chapter explained, you must remain calm if the error log persists after installing the module.Importing the Binary and Psycopg Packages

You can complete the debugging procedure and prevent complications by importing the relevant binary packages. In addition, you will not compromise other properties, which is terrific when working on sophisticated projects.

You can learn how to implement this solution in the following example:

import psycopg2

# Connect to your postgres DB

conn = psycopg2.connect (“dbname = test user = postgres”)

# Open a cursor to perform database operations

cur = conn.cursor()

# Execute a query

cur.execute (“SELECT * FROM my_data”)

# Retrieve query results

records = cur.fetchall()

This code snippet completes the debugging approach and exemplifies that the solution sometimes requires only a few code lines. In addition, isolating the malfunctioned document is unnecessary, saving you some time.

Conclusion

The module named ‘psycopg2’ Python3 mistake happens when the machine cannot find the necessary library. Nevertheless, nothing stopped us from creating the best debugging guide, so let’s revise the vital points:

  • We experienced a similar error log when forgetting to install the psycopg file or command
  • Running the flexible server with inadequate libraries recreates the code exception
  • You can fix the psycopg2 error by installing the adequate module for the main functions
  • Importing the binary and psycopg packages to render the values is an alternative solution

This article proved debugging complex mistakes and issues is sometimes fun and takes a few minutes. You will experience no significant obstacles when repairing your forgotten project.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

When I try to import psycopg2 it show below log for me:

Traceback (most recent call last):
  File "D:/Desktop/learn/python/webcatch/appserver/testpgsql.py", line 2, in <module>
    import psycopg2
  File "D:/Desktop/learn/python/webcatch/appserver/webcatch/lib/site-packages/psycopg2-2.6.1-py3.5-win32.egg/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: No module named 'psycopg2._psycopg'

How can I solve it?
My platform is win10 (64) and version is python 3.5

Tadhg McDonald-Jensen's user avatar

asked Mar 19, 2016 at 14:38

sappy's user avatar

4

Eureka! I pulled my hair out for 2 days trying to get this to work. Enlightenment came from this SO Question. Simply stated, you probably installed psycopg2 x64 version like I did, not realizing your python version was 32-bit. Unistall your current psycopg2, then:

Download: psycopg2-2.6.1.win32-py3.4-pg9.4.4-release.exe from HERE, then run the following in a Terminal:

C:\path\to\project> easy_install /path/to/psycopg2-2.6.1.win32-py3.4-pg9.4.4-release.exe
C:\path\to\project> python manage.py makemigrations
C:\path\to\project> python manage.py migrate

You may also need to (re)create super user with:

C:\path\to\project> python manage.py createsuperuser

Community's user avatar

answered Jun 14, 2016 at 18:26

Matthew Weber's user avatar

4

I had the same problem, solved it in this way:

Reinstall the package psycopg2 using pip (by default installed with python 3)

On Linux:

pip uninstall psycopg2

Confirm with (y) and then:

pip install psycopg2

On Windows I add the prefix ('python -m') to the commands above.
I think the problem occurs when you change the version of Python. (Even between minor versions such as Python 3.5 and 3.6).

answered Mar 30, 2018 at 15:27

JoDavid's user avatar

JoDavidJoDavid

4033 silver badges8 bronze badges

3

I am using psycopg in an AWS Glue Job, where is harder to follow the instructions listed in the other answers.

What I did is installing psycopg2-binary into a directory and zip up the contents of that directory:

mkdir psycopg2-binary
cd psycopg2-binary
pip install psycopg2-binary -t  .
# in case using python3:
# python3 -m pip install --system psycopg2-binary -t  .
zip -r9 psycopg2.zip *

I then copied psycopg2.zip to an S3 bucket and add it as an extra Python library under «Python library path» in the Glue Spark job.

I then launched the job with the following script to verify if psycopg2 is present (the zip file will be downloaded by Glue into the directory in which the Job script is located)

from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
import sys
import os
import zipfile

## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

zip_ref = zipfile.ZipFile('./psycopg2.zip', 'r')
print os.listdir('.')
zip_ref.extractall('/tmp/packages')
zip_ref.close()
sys.path.insert(0, '/tmp/packages')

import psycopg2
print(psycopg2.__version__)

job.commit()

answered Oct 9, 2019 at 13:46

Vzzarr's user avatar

VzzarrVzzarr

4,6602 gold badges43 silver badges81 bronze badges

1

This also happens to me in new Ubuntu 18.04. It is caused by missing one file _psycopg.py in the /usr/local/lib/python3.7/site-packages/psycopg2.

It is fixed by:

  1. remove the old psycopg2 from your machine pip3 uninstall psycopg2.
  2. download new pyscopg2 manually from the official page http://initd.org/psycopg/tarballs/PSYCOPG-2-7/psycopg2-2.7.7.tar.gz
  3. tar xvf psycopg2-2.7.7.tar.gz
  4. python setup.py build
  5. sudo python setup.py install

answered Mar 1, 2019 at 4:58

Saray Chak's user avatar

Saray ChakSaray Chak

691 silver badge6 bronze badges

1

I had this happen in Linux using Python 3.7. It is caused by missing one file _psycopg.cpython-37m-x86_64-linux-gnu.so in the /usr/local/lib/python3.7/site-packages/psycopg2.
I downloaded _psycopg.cpython-37m-x86_64-linux-gnu.so from https://github.com/jkehler/awslambda-psycopg2/tree/master/psycopg2-3.7, and Copied this file into my anaconda lib.

answered Jul 8, 2021 at 7:05

土豆陈's user avatar

I had this happen in Linux using Python 2 because I had accidentally had my PYTHONPATH set to Python 3 libraries, and it was trying to load the python3 version of psycopg2. Solution was to unset PYTHONPATH.

answered Feb 8, 2017 at 2:20

sudo's user avatar

sudosudo

5,6245 gold badges40 silver badges78 bronze badges

I had the same error on Windows, this worked for me:
pip install -U psycopg2

I had an older version installed, must have depreciated

answered Jun 5, 2019 at 13:46

Ryan L's user avatar

Ryan LRyan L

1111 silver badge2 bronze badges

I came to know that most times the WINDOWS packaging does not go fine with LAMBDA.

I faced same issue while running LAMBDA with WINDOWS installed 3rd party pscyopg2 packaging.

Solution:

step1>
I installed psycopg2 in Linux.
Copied both the directories psycopg2_binary-2.8.2.dist-info and psycopg2 from Linux to windows.

step2>
Along with source *.py, packaged with copied 3rd party dependencies psycopg2 in windows to *.zip file

step3>
Upload the file to LAMBDA — Here it goes, It runs successfully without any error.

Community's user avatar

answered Apr 15, 2019 at 13:30

Deep's user avatar

0

Windows 10 with conda environment manager (fresh install of Django, wagtail with PostgreSQL), had the same error. Removed psycopg2

conda remove -n myenv psycopg2

it updated some packages, removed others (it also removed django, wagtail…). Then installed psycopg2 back

conda install -n myenv psycopg2

Tested it, import worked

python
>>> import psycopg2

Installed django, wagtail back. python manage.py migrate now populated PostgreSQL.

answered Sep 6, 2022 at 14:19

Vladislav Povorozniuc's user avatar

In my case, it was other site-packages that was exposed by installing pgcli, uninstalling pgcli resolved the issue for the time being.

This somehow penetrated virtualenv too.

answered Sep 24, 2022 at 0:25

Heechul Ryu's user avatar

Heechul RyuHeechul Ryu

4716 silver badges6 bronze badges

Skip to content

psycopg2 module is used to connect to PostgreSQL Server using Python. But, if you receive below error means,you have not installed psycopg2 module.

Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'psycopg2'

Solution:


We have to install psycopg2 on Windows or Linux.

1) Install psycopg2 on windows with the below command.

pip install psycopg2 or pip install psycopg2-binary or pip3 install psycopg2

C:\Users\karunakar\Desktop\Py Practice>pip install psycopg2 Collecting psycopg2 Downloading https://files.pythonhosted.org/packages/79/ad/327e9c1e09b91e57294eb9a38492fcb000f15c028a1b716714fee5be802e/psycopg2-2.8.4-cp38-cp38-win32.whl (986kB) |████████████████████████████████| 993kB 133kB/s Installing collected packages: psycopg2 Successfully installed psycopg2-2.8.4

2. Install psycopg2 on Linux.

sudo apt-get install libpq-dev

3. Now try to import the psycopg2 module. Then, you will not get the error.

Many developers face the issue of the No module named ‘psycopg2’ when they try to take their project to the production level. With the help of this article, we will understand the cause of the error and the possible solutions to avoid them. Let’s dive in.

What is ‘psycopg2’?

‘psycopg2’ is the most popular database adapter dealing in PostgreSQL. Its core is to completely implement the Python DB API 2.0 specification and the thread-safety. That means it can allow several threads to share a standard connection. It can easily handle concurrent insertion and deletion in an application. It can create or destroy lots of connections simultaneously.

Architechture behind ‘psycopg2’

‘psycopg2’ uses a libpq wrapper, which implements the C programming language interface. It consists of a set of library functions that allow client programs to receive the results of the queries passed to the PostgreSQL backend server.

Cause behind the error: No module named ‘psycopg2’

To execute the program smoothly, some pre-requisites should be met. Failing to meet these requirements will trigger import errors during the compilation.

Pre-requisites are :

  1. Python Version
    • 3.6 to 3.9
  2. PostgreSQL server versions
    • 7.4 to 13
  3. PostgreSQL client library version
    • from 9.1
  4. C compiler
  5. Package such as python-dev or python3-dev to install python header files.
  6. libpq-dev package containing libpq header files.
  7. pg-config file should be present in the PATH file. It compiles ‘psycopg2

If the system does not meet the above requirements, the ‘psycopg2’ module will not be installed, leading to no modules name ‘psycopg2’ error. This error is often viewed by programmers who don’t have a C compiler in their system. As the binaries fail to install, the module will not work.

Resolving the issue: No module named ‘psycopg2’

To resolve the issue, we must satisfy all the pre-requisites laid by the ‘psycopg2’ to meet its build requirements. However, pyscopg2 also provides us with a binary package with its versions of C libraries, libpq, and libssl, which will be used regardless of other libraries available to the client.

Perform these commands to resolve the issue:

pip uninstall psycopg2
pip install psycopg2-binary

Running the above commands will solve the problem, but the installation may fail in a few cases due to a non-supportive environment. Follow these steps to install the precompiled library –

  1. Go to the Precompiled Library Packages list.
  2. Then download the wheel file (.whl) for the psycopg module.
  3. Then use the command pip install <file>.whl to install the library using downloaded wheel file.

Using the above steps will guarantee installing psycopg2 on your computer.

Working On Incorrect Virtual Enviornment?

Many “No module named psycopg2” errors occur due to working on incorrect virtual environments and installing the ‘psycopg2’ on a different environment. Suppose you have two versions of python3 installed, and how will you install ‘psycopg2’ to a specific python?

Use the following command to call your python and install the package in your respective environment –

python3 -m pip install psycopg2

This will ensure that you install the psycopg2 module in the working environment. Hopefully, this resolves the issue. Moreover, if you face the C Compiler issues in this method, use the precompiled method as mentioned last way.

Recommended Reading | [Solved] No Module Named Numpy in Python

Resolving No module named ‘psycopg2’ in AWS EC2 lambda/ Linux OS

However, one cannot rely on binary packages if they are using them in production, and we should build the ‘psycopg2’ from the source. Because upgrading the system libraries will not upgrade the libraries used by ‘psycopg2'. Hence, there might be a dependencies error.

One can perform these commands to solve the problem

sudo apt install gcc g++ build-essential
sudo apt install python3-dev
sudo apt install libpq-dev
python -m pip install psycopg2

How to solve the No module named ‘psycopg2’ Error in Conda/Anaconda?

Conda or Anaconda has its virtual environment. So to work ‘psycopg2’, you have to install psycopg2 on Conda Environment. Use conda install psycopg2 to install psycopg2.

How to solve the No module named ‘psycopg2’ Error in Jupyter?

In most cases, Jupyter Notebook works in the anaconda environment. Use the conda install psycopg2 command to install the package in Jupyter. If it’s not working on Anaconda Environment, you have to find the location of the working environment and install the package there.

Conclusion

So, in this way, one can resolve the import error related to the PostgreSQL connection. A quick tip is to keep in mind the requisites we should follow before executing any program. We can permanently activate a python virtual window and maintain that virtual window according to the project’s needs. Now it’s your time to leverage the DB connection and create fantastic projects with ‘psycopg2’ and PostgreSQL.

Bon Codage!

Other Errors You Might Get

  • Why SPIdev for Windows is a Game-Changer: Everything You Need to Know

    Why SPIdev for Windows is a Game-Changer: Everything You Need to Know

    October 2, 2023

  • Print Vs Return in Python: The Ultimate Showdown

    Print Vs Return in Python: The Ultimate Showdown

    by Namrata GulatiSeptember 24, 2023

  • Python input() Vs raw_input(): Which One to Choose?

    Python input() Vs raw_input(): Which One to Choose?

    by Namrata GulatiSeptember 24, 2023

  • Why Python Fnmatch Library is a Game-Changer for File Management

    Why Python Fnmatch Library is a Game-Changer for File Management

    by Namrata GulatiSeptember 24, 2023

  • Mouse utility для windows 10
  • Mount and blade история героя не запускается на windows 10
  • Modulenotfounderror no module named pip windows
  • Mobilego скачать бесплатно на русском для windows 10
  • Mouse pointers for windows 10