Modulenotfounderror no module named psycopg2 windows

I can confirm psycopg2 is install (using conda install -c anaconda psycopg2) but the it seems psycopg2 cannot be imported to my python script or the interpreter is unable to locate it. I also tried

I can confirm psycopg2 is install (using conda install -c anaconda psycopg2) but the it seems psycopg2 cannot be imported to my python script or the interpreter is unable to locate it. I also tried installing using pip3, requirements are satisfied, meaning psycopg2 is already istalled, but cannot understand why I script isn’t able to import it. Using Mac (OS v10.14.4)

$ python create_tables.py
Traceback (most recent call last):
  File "create_tables.py", line 1, in <module>
    import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

$ pip3 install psycopg2
Requirement already satisfied: psycopg2 in /usr/local/lib/python3.7/site-packages (2.8.2)
$ pip3 install psycopg2-binary
Requirement already satisfied: psycopg2-binary in /usr/local/lib/python3.7/site-packages (2.8.2)
python -V
Python 3.7.0

Any idea why this happen?

EDIT: create_table.py

import psycopg2
from config import config


def create_tables():
    """ create tables in the PostgreSQL database"""
    commands = (
        """
        CREATE TABLE vendors (
            vendor_id SERIAL PRIMARY KEY,
            vendor_name VARCHAR(255) NOT NULL
        )
        """,
        """ CREATE TABLE parts (
                part_id SERIAL PRIMARY KEY,
                part_name VARCHAR(255) NOT NULL
                )
        """,
        """
        CREATE TABLE part_drawings (
                part_id INTEGER PRIMARY KEY,
                file_extension VARCHAR(5) NOT NULL,
                drawing_data BYTEA NOT NULL,
                FOREIGN KEY (part_id)
                REFERENCES parts (part_id)
                ON UPDATE CASCADE ON DELETE CASCADE
        )
        """,
        """
        CREATE TABLE vendor_parts (
                vendor_id INTEGER NOT NULL,
                part_id INTEGER NOT NULL,
                PRIMARY KEY (vendor_id , part_id),
                FOREIGN KEY (vendor_id)
                    REFERENCES vendors (vendor_id)
                    ON UPDATE CASCADE ON DELETE CASCADE,
                FOREIGN KEY (part_id)
                    REFERENCES parts (part_id)
                    ON UPDATE CASCADE ON DELETE CASCADE
        )
        """)
    conn = None
    try:
        # read the connection parameters
        params = config()
        # connect to the PostgreSQL server
        conn = psycopg2.connect(**params)
        cur = conn.cursor()
        # create table one by one
        for command in commands:
            cur.execute(command)
        # close communication with the PostgreSQL database server
        cur.close()
        # commit the changes
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()


if __name__ == '__main__':
    create_tables()

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:

envScriptsactivate

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!

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

  • [Fixed] Module Seaborn has no Attribute Histplot Error

    [Fixed] Module Seaborn has no Attribute Histplot Error

    January 18, 2023

  • Thonny: Text Wrapping Made Easy

    Thonny: Text Wrapping Made Easy

    by Rahul Kumar YadavJanuary 18, 2023

  • [Fixed] JavaScript error: IPython is Not Defined

    [Fixed] JavaScript error: IPython is Not Defined

    by Rahul Kumar YadavJanuary 18, 2023

  • [Fixed] “io.unsupportedoperation not readable” Error

    [Fixed] “io.unsupportedoperation not readable” Error

    by Rahul Kumar YadavJanuary 18, 2023

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:UserskarunakarDesktopPy 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.

Quick Fix: Python raises the ImportError: No module named 'psycopg2' when it cannot find the library psycopg2. The most frequent source of this error is that you haven’t installed psycopg2 explicitly with pip install psycopg2. Alternatively, you may have different Python versions on your computer, and psycopg2 is not installed for the particular version you’re using.

Problem Formulation

You’ve just learned about the awesome capabilities of the psycopg2 library and you want to try it out, so you start your code with the following statement:

import psycopg2

This is supposed to import the Pandas library into your (virtual) environment. However, it only throws the following ImportError: No module named psycopg2:

>>> import psycopg2
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

Solution Idea 1: Install Library psycopg2

The most likely reason is that Python doesn’t provide psycopg2 in its standard library. You need to install it first!

Before being able to import the Pandas module, you need to install it using Python’s package manager pip. Make sure pip is installed on your machine.

To fix this error, you can run the following command in your Windows shell:

$ pip install psycopg2

This simple command installs psycopg2 in your virtual environment on Windows, Linux, and MacOS. It assumes that your pip version is updated. If it isn’t, use the following two commands in your terminal, command line, or shell (there’s no harm in doing it anyways):

$ python -m pip install --upgrade pip
$ pip install pandas

💡 Note: Don’t copy and paste the $ symbol. This is just to illustrate that you run it in your shell/terminal/command line.

Solution Idea 2: Fix the Path

The error might persist even after you have installed the psycopg2 library. This likely happens because pip is installed but doesn’t reside in the path you can use. Although pip may be installed on your system the script is unable to locate it. Therefore, it is unable to install the library using pip in the correct path.

To fix the problem with the path in Windows follow the steps given next.

Step 1: Open the folder where you installed Python by opening the command prompt and typing where python

Step 2: Once you have opened the Python folder, browse and open the Scripts folder and copy its location. Also verify that the folder contains the pip file.

Step 3: Now open the Scripts directory in the command prompt using the cd command and the location that you copied previously.

Step 4: Now install the library using pip install psycopg2 command. Here’s an analogous example:

After having followed the above steps, execute our script once again. And you should get the desired output.

Other Solution Ideas

  • The ModuleNotFoundError may appear due to relative imports. You can learn everything about relative imports and how to create your own module in this article.
  • You may have mixed up Python and pip versions on your machine. In this case, to install psycopg2 for Python 3, you may want to try python3 -m pip install psycopg2 or even pip3 install psycopg2 instead of pip install psycopg2
  • If you face this issue server-side, you may want to try the command pip install --user psycopg2
  • If you’re using Ubuntu, you may want to try this command: sudo apt install psycopg2
  • You can check out our in-depth guide on installing psycopg2 here.
  • You can also check out this article to learn more about possible problems that may lead to an error when importing a library.

Understanding the “import” Statement

import psycopg2

In Python, the import statement serves two main purposes:

  • Search the module by its name, load it, and initialize it.
  • Define a name in the local namespace within the scope of the import statement. This local name is then used to reference the accessed module throughout the code.

What’s the Difference Between ImportError and ModuleNotFoundError?

What’s the difference between ImportError and ModuleNotFoundError?

Python defines an error hierarchy, so some error classes inherit from other error classes. In our case, the ModuleNotFoundError is a subclass of the ImportError class.

You can see this in this screenshot from the docs:

You can also check this relationship using the issubclass() built-in function:

>>> issubclass(ModuleNotFoundError, ImportError)
True

Specifically, Python raises the ModuleNotFoundError if the module (e.g., psycopg2) cannot be found. If it can be found, there may be a problem loading the module or some specific files within the module. In those cases, Python would raise an ImportError.

If an import statement cannot import a module, it raises an ImportError. This may occur because of a faulty installation or an invalid path. In Python 3.6 or newer, this will usually raise a ModuleNotFoundError.

Related Videos

The following video shows you how to resolve the ImportError:

How to Fix : “ImportError: Cannot import name X” in Python?

The following video shows you how to import a function from another folder—doing it the wrong way often results in the ModuleNotFoundError:

How to Call a Function from Another File in Python?

How to Fix “ModuleNotFoundError: No module named ‘psycopg2′” in PyCharm

If you create a new Python project in PyCharm and try to import the psycopg2 library, it’ll raise the following error message:

Traceback (most recent call last):
  File "C:/Users/.../main.py", line 1, in <module>
    import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

Process finished with exit code 1

The reason is that each PyCharm project, per default, creates a virtual environment in which you can install custom Python modules. But the virtual environment is initially empty—even if you’ve already installed psycopg2 on your computer!

Here’s a screenshot exemplifying this for the pandas library. It’ll look similar for psycopg2.

The fix is simple: Use the PyCharm installation tooltips to install Pandas in your virtual environment—two clicks and you’re good to go!

First, right-click on the pandas text in your editor:

Second, click “Show Context Actions” in your context menu. In the new menu that arises, click “Install Pandas” and wait for PyCharm to finish the installation.

The code will run after your installation completes successfully.

As an alternative, you can also open the Terminal tool at the bottom and type:

$ pip install psycopg2

If this doesn’t work, you may want to set the Python interpreter to another version using the following tutorial: https://www.jetbrains.com/help/pycharm/2016.1/configuring-python-interpreter-for-a-project.html

You can also manually install a new library such as psycopg2 in PyCharm using the following procedure:

  • Open File > Settings > Project from the PyCharm menu.
  • Select your current project.
  • Click the Python Interpreter tab within your project tab.
  • Click the small + symbol to add a new library to the project.
  • Now type in the library to be installed, in your example Pandas, and click Install Package.
  • Wait for the installation to terminate and close all popup windows.

Here’s an analogous example:

Here’s a full guide on how to install a library on PyCharm.

  • How to Install a Library on PyCharm

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Introduction

This is an article with a specific topic about how to solve error message as it exists in the title of the article. It occurs when a django application runs. It happens after adding the following content in the settings.py script inside the project folder :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'xxxx',
        'USER': 'postgres',
        'PASSWORD' : '',
        'HOST' : 'xxx.xxx.xxx.xxx',
        'PORT' : 'xxxx',
    }
}

The above line configurations is a specific script for connecting the django application to PostgreSQL database server. Suddenly, after saving the file, the runserver application execution is generating error. The error message is ModuleNotFoundError: No module named ‘psycopg2’. The following is the complete output error message :

user@hostname:~/python/my-django/users$ python3 manage.py makemigrations
Traceback (most recent call last):e
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 20, in 
    import psycopg2 as Database
ModuleNotFoundError: No module named 'psycopg2'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 21, in 
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
    django.setup()
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "", line 994, in _gcd_import
  File "", line 971, in _find_and_load
  File "", line 955, in _find_and_load_unlocked
  File "", line 665, in _load_unlocked
  File "", line 678, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in 
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in 
    class AbstractBaseUser(models.Model):
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/db/models/base.py", line 117, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/db/models/base.py", line 321, in add_to_class
    value.contribute_to_class(cls, name)
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/db/models/options.py", line 204, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "v/python/django-env/lib/python3.6/site-packages/django/db/__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/db/utils.py", line 201, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/home/user/python/django-env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 24, in 
    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'

Solving the Problem

To solve the above problem, there are several solutions and those solutions have a connection with one another. But the most important thing is the focus of the solution is in the existance of the ‘psycopg2’. How can the module with the name of ‘psycopg2’ can be available for further usage in the django application.  There are several steps or solution to solve the problem. The following is the list of the alternative steps or solution :

1. Installing the psycopg2 package.

2. Install the psycopg2 package to the virtual environment.

In the following section, there will be a further detail explanation about the above steps for solving the problem.

Installing psycopg2 package to the operating system using apt tool

Since it is the Linux Ubuntu distribution, execute the following command to install the ‘psycopg2’ module :

(django-env) (base) user@hostname:~/python/my-django/users$ sudo apt-get -y install python3-psycopg2
[sudo] password for user: 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Suggested packages:
  python-psycopg2-doc
The following NEW packages will be installed:
  python3-psycopg2
0 upgraded, 1 newly installed, 0 to remove and 5 not upgraded.
Need to get 152 kB of archives.
After this operation, 838 kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-psycopg2 amd64 2.7.4-1 [152 kB]
Fetched 152 kB in 2s (85.6 kB/s)                    
Selecting previously unselected package python3-psycopg2.
(Reading database ... 328999 files and directories currently installed.)
Preparing to unpack .../python3-psycopg2_2.7.4-1_amd64.deb ...
Unpacking python3-psycopg2 (2.7.4-1) ...
Setting up python3-psycopg2 (2.7.4-1) ...
(django-env) (base) user@hostname:~/python/my-django/users$ 

The above command execution is relying on the apt tool program. Just make sure to choose the correct package name since the chosen package for the installation above is using python3. So, the package name for installation is ‘python3-psycopg. Make sure to search the compatible package using ‘apt search’ command.

Apparently, in this case, after executing the above command for installing psycopg2 to the operating system, the error message still occurs. So, if the error message is still occurs, just do the following step as another action to complete the solution.

Installing psycopg2 module in the python virtual environment using pip

The following is the command for executing psycopg2 to the running python virtual environment. The python virtual environment is ‘django-env’. The command for installing psycopg2 module is ‘pip install psycopg2’.

(django-env) (base) user@hostname:~/python/my-django/users$ pip install psycopg2
Collecting psycopg2
Downloading https://files.pythonhosted.org/packages/5c/1c/6997288da181277a0c29bc39a5f9143ff20b8c99f2a7d059cfb55163e165/psycopg2-2.8.3.tar.gz (377kB)
100% |████████████████████████████████| 378kB 1.4MB/s
Building wheels for collected packages: psycopg2
Running setup.py bdist_wheel for psycopg2 ... error
Complete output from command /home/user/python/django-env/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-nf3652og/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpb8vrk172pip-wheel- --python-tag cp36:
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: -c --help [cmd1 cmd2 ...]
or: -c --help-commands
or: -c cmd --help

error: invalid command 'bdist_wheel'

----------------------------------------
Failed building wheel for psycopg2
Running setup.py clean for psycopg2
Failed to build psycopg2
Installing collected packages: psycopg2
Running setup.py install for psycopg2 ... error
Complete output from command /home/user/python/django-env/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-nf3652og/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-zxhvlzhf-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/user/python/django-env/include/site/python3.6/psycopg2:
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.6
creating build/lib.linux-x86_64-3.6/psycopg2
copying lib/_json.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/compat.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/tz.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/_range.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/extras.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/errorcodes.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/extensions.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/__init__.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/sql.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/pool.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/_lru_cache.py -> build/lib.linux-x86_64-3.6/psycopg2
copying lib/errors.py -> build/lib.linux-x86_64-3.6/psycopg2
running build_ext
building 'psycopg2._psycopg' extension
creating build/temp.linux-x86_64-3.6
creating build/temp.linux-x86_64-3.6/psycopg
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DPSYCOPG_VERSION=2.8.3 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=100009 -DHAVE_LO64=1 -I/home/user/python/django-env/include -I/usr/include/python3.6m -I. -I/usr/include/postgresql -I/usr/include/postgresql/10/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.6/psycopg/psycopgmodule.o -Wdeclaration-after-statement
In file included from psycopg/psycopgmodule.c:27:0:
./psycopg/psycopg.h:34:10: fatal error: Python.h: No such file or directory
#include
^~~~~~~~~~
compilation terminated.

It appears you are missing some prerequisite to build the package from source.

You may install a binary package by installing 'psycopg2-binary' from PyPI.
If you want to install psycopg2 from source, please install the packages
required for the build and try again.

For further information please check the 'doc/src/install.rst' file (also at
<http://initd.org/psycopg/docs/install.html>).
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Command "/home/user/python/django-env/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-nf3652og/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-zxhvlzhf-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/user/python/django-env/include/site/python3.6/psycopg2" failed with error code 1 in /tmp/pip-build-nf3652og/psycopg2/
(django-env) (base) user@hostname:~/python/my-django/users$


Installation of psycopg2-binary module in the python virtual environment using pip

Apparently, the solution in the previous step failed. There is an information about how to proceed the installation. It gives a solution to install a binary package with the name of ‘psycopg2-binary’. The following is the command execution :

(django-env) (base) user@hostname:~/python/my-django/users$ pip install psycopg2-binary==2.7.4
Collecting psycopg2-binary==2.7.4
Downloading https://files.pythonhosted.org/packages/5f/0b/aa7078d3f6d27d951c38b6a1f4b99b71b2caecebb2921b2d808b5bf0e2e0/psycopg2_binary-2.7.4-cp36-cp36m-manylinux1_x86_64.whl (2.7MB)
100% |████████████████████████████████| 2.7MB 194kB/s
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.7.4
(django-env) (base) user@hostname:~/python/my-django/users$

In the output above, the python virtual environment is ‘django-env’. According to the output message of the running django web server, after the execution of the above step ends in a success, the error message disappear and the problem solved.

PostgreSQL database is the most used SQL database. Psycopg2 is the most popular PostgreSQL database adapter for the Python programming language. Using it you can connect, update, insert, more efficiently on your database. However, sometimes many programmers find no module named psycopg2 error. And in this entire tutorial, you will know how to fix no module named psycopg2.

Most of the time this error comes when you have not properly installed the psycopg3 in your system. For example, if I type the following code and run it will get the No module named psycopg2 error.

import psycopg2

You will get the following error when you run the code.

ModuleNotFoundError: no module named "psycopg2 "

Methods to Fix the psycopg2 error

Now the questions come about how to fix this error. There are many methods to fix it and it depends upon your system.

Method 1: Install the psycopg2-binary

The first method that can solve this error is to install psycopg2-binary instead of psycopg2. You can install it using the pip command.

For python 2.xx version

pip install psycopg2-binary

For python 3.xx version

pip3 install psycopg2-binary

It will successfully install the module and now you will run the code then you will not get the No module named psycopg2 error.

Note: To check the python version on your system run the below command on your system terminal.

python --version

Checking the version of python on windows

Checking the version of python on windows

Method 2: Update the pip command

Sometimes you are unable to install psycopg2 due to the corrupted or outdated pip command.  To fix the error you have to install or update the pip command.

The pip command comes with the python. But in case you want to install it then you will use the following command. But before that, you have to download the get-pip.py. After that go to the downloaded directory and Copy the below command and run the python file on your terminal.

python get-pip.py

It will successfully install the pip package on your system. Now using it install the psycopg2. It will successfully remove the No module named psycopg2 error.

These are the two popular methods to solve the No module  psycopg2 error. I hope using this tutorial you have solved the issue. Even if the issue remains then you can contact us for more help.

This article will help you, how to fix the ModuleNotFoundError: No module named ‘psycopg2’, No module named ‘flask_sqlalchemy’ or ModuleNotFoundError: No module named ‘MODULE_NAME’  in python.

Solution – ModuleNotFoundError: No module named ‘psycopg2’

{Read:- 5 Ways to Improve SEO on Your WordPress Site }

To fix the No module named ‘psycopg2’ error, you have to install the dependent library as well as psycopg2 Module.

Python 3-

sudo apt-get install libpq-dev

pip3 install psycopg2

Python 2-

sudo apt-get install libpq-dev

pip install psycopg2

Solution – ModuleNotFoundError: No module named ‘flask_sqlalchemy’

Python 3-

pip3 install flask_sqlalchemy

pip3 install sqlalchemy

Python 2-

pip install flask_sqlalchemy

pip install sqlalchemy

Solution – ModuleNotFoundError: No module named ‘MODULE_NAME’

{Read:- How to Build a WordPress Site in 1 Day }

Python 3-

Python 2-

Понравилась статья? Поделить с друзьями:
  • Modern setup host что это грузит диск windows 10
  • Modulenotfounderror no module named pil windows
  • Modern setup host при установке windows 10
  • Modulenotfounderror no module named matplotlib windows
  • Modern setup host ошибка обновления windows