Psycopg install error

Psycopg is a PostgreSQL adapter for the Python programming language. It is a wrapper for the libpq, the official PostgreSQL client library.

Psycopg is a PostgreSQL adapter for the Python programming language. It is a
wrapper for the libpq, the official PostgreSQL client library.

Quick Install¶

For most operating systems, the quickest way to install Psycopg is using the
wheel package available on PyPI:

$ pip install psycopg2-binary

This will install a pre-compiled binary version of the module which does not
require the build or runtime prerequisites described below. Make sure to use
an up-to-date version of pip (you can upgrade it using something
like pip install -U pip).

You may then import the psycopg2 package, as usual:

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()

psycopg vs psycopg-binary¶

The psycopg2-binary package is meant for beginners to start playing
with Python and PostgreSQL without the need to meet the build
requirements.

If you are the maintainer of a published package depending on psycopg2
you shouldn’t use psycopg2-binary as a module dependency. For
production use you are advised to use the source distribution.

The binary packages come with their own versions of a few C libraries,
among which libpq and libssl, which will be used regardless of other
libraries available on the client: upgrading the system libraries will not
upgrade the libraries used by psycopg2. Please build psycopg2 from
source if you want to maintain binary upgradeability.

Warning

The psycopg2 wheel package comes packaged, among the others, with its
own libssl binary. This may create conflicts with other extension
modules binding with libssl as well, for instance with the Python
ssl module: in some cases, under concurrency, the interaction between
the two libraries may result in a segfault. In case of doubts you are
advised to use a package built from source.

Change in binary packages between Psycopg 2.7 and 2.8¶

In version 2.7.x, pip install psycopg2 would have tried to install
automatically the binary package of Psycopg. Because of concurrency problems
binary packages have displayed, psycopg2-binary has become a separate
package, and from 2.8 it has become the only way to install the binary
package.

If you are using Psycopg 2.7 and you want to disable the use of wheel binary
packages, relying on the system libraries available on your client, you
can use the pip --no-binary option, e.g.:

$ pip install --no-binary :all: psycopg2

which can be specified in your requirements.txt files too, e.g. use:

psycopg2>=2.7,<2.8 --no-binary psycopg2

to use the last bugfix release of the psycopg2 2.7 package, specifying to
always compile it from source. Of course in this case you will have to meet
the build prerequisites.

Prerequisites¶

The current psycopg2 implementation supports:

  • Python versions from 3.6 to 3.11

  • PostgreSQL server versions from 7.4 to 15

  • PostgreSQL client library version from 9.1

Note

Not all the psycopg2 versions support all the supported Python versions.

Please see the release notes to verify when the support for
a new Python version was added and when the support for an old Python
version was removed.

Build prerequisites¶

The build prerequisites are to be met in order to install Psycopg from source
code, from a source distribution package, GitHub or from PyPI.

Psycopg is a C wrapper around the libpq PostgreSQL client library. To install
it from sources you will need:

  • A C compiler.

  • The Python header files. They are usually installed in a package such as
    python-dev or python3-dev. A message such as error: Python.h: No
    such file or directory
    is an indication that the Python headers are
    missing.

  • The libpq header files. They are usually installed in a package such as
    libpq-dev. If you get an error: libpq-fe.h: No such file or directory
    you are missing them.

  • The pg_config program: it is usually installed by the
    libpq-dev package but sometimes it is not in a PATH directory.
    Having it in the PATH greatly streamlines the installation, so try
    running pg_config --version: if it returns an error or an unexpected
    version number then locate the directory containing the pg_config
    shipped with the right libpq version (usually
    /usr/lib/postgresql/X.Y/bin/) and add it to the PATH:

    $ export PATH=/usr/lib/postgresql/X.Y/bin/:$PATH
    

    You only need pg_config to compile psycopg2, not for its
    regular usage.

Once everything is in place it’s just a matter of running the standard:

or, from the directory containing the source code:

$ python setup.py build
$ python setup.py install

Runtime requirements¶

Unless you compile psycopg2 as a static library, or you install it from a
self-contained wheel package, it will need the libpq library at runtime
(usually distributed in a libpq.so or libpq.dll file). psycopg2
relies on the host OS to find the library if the library is installed in a
standard location there is usually no problem; if the library is in a
non-standard location you will have to tell Psycopg how to find it,
which is OS-dependent (for instance setting a suitable
LD_LIBRARY_PATH on Linux).

Note

The libpq header files used to compile psycopg2 should match the
version of the library linked at runtime. If you get errors about missing
or mismatching libraries when importing psycopg2 check (e.g. using
ldd) if the module psycopg2/_psycopg.so is linked to the
right libpq.so.

Note

Whatever version of libpq psycopg2 is compiled with, it will be
possible to connect to PostgreSQL servers of any supported version: just
install the most recent libpq version or the most practical, without
trying to match it to the version of the PostgreSQL server you will have
to connect to.

Non-standard builds¶

If you have less standard requirements such as:

  • creating a debug build,

  • using pg_config not in the PATH,

then take a look at the setup.cfg file.

Some of the options available in setup.cfg are also available as command
line arguments of the build_ext sub-command. For instance you can specify
an alternate pg_config location using:

$ python setup.py build_ext --pg-config /path/to/pg_config build

Use python setup.py build_ext --help to get a list of the options
supported.

Creating a debug build¶

In case of problems, Psycopg can be configured to emit detailed debug
messages, which can be very useful for diagnostics and to report a bug. In
order to create a debug package:

  • Download and unpack the Psycopg source package (the .tar.gz
    package).

  • Edit the setup.cfg file adding the PSYCOPG_DEBUG flag to the
    define option.

  • Compile and install the package.

  • Set the PSYCOPG_DEBUG environment variable:

  • Run your program (making sure that the psycopg2 package imported is the
    one you just compiled and not e.g. the system one): you will have a copious
    stream of informations printed on stderr.

Non-standard Python Implementation¶

The psycopg2 package is the current mature implementation of the adapter: it
is a C extension and as such it is only compatible with CPython. If you want
to use Psycopg on a different Python implementation (PyPy, Jython, IronPython)
there is a couple of alternative:

  • a Ctypes port, but it is not as mature as the C implementation yet
    and it is not as feature-complete;

  • a CFFI port which is currently more used and reported more efficient on
    PyPy, but please be careful of its version numbers because they are not
    aligned to the official psycopg2 ones and some features may differ.

Running the test suite¶

Once psycopg2 is installed you can run the test suite to verify it is
working correctly. From the source directory, you can run:

$ python -c "import tests; tests.unittest.main(defaultTest='tests.test_suite')" --verbose

The tests run against a database called psycopg2_test on UNIX socket and
the standard port. You can configure a different database to run the test by
setting the environment variables:

  • PSYCOPG2_TESTDB

  • PSYCOPG2_TESTDB_HOST

  • PSYCOPG2_TESTDB_PORT

  • PSYCOPG2_TESTDB_USER

The database should already exist before running the tests.

If you still have problems¶

Try the following. In order:

  • Read again the Build prerequisites.

  • Read the FAQ.

  • Google for psycopg2 your error message. Especially useful the week
    after the release of a new OS X version.

  • Write to the Mailing List.

  • If you think that you have discovered a bug, test failure or missing feature
    please raise a ticket in the bug tracker.

  • Complain on your blog or on Twitter that psycopg2 is the worst package
    ever and about the quality time you have wasted figuring out the correct
    ARCHFLAGS. Especially useful from the Starbucks near you.

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

  • “Other Commands Don’t Work After on_message” in Discord Bots

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Best Ways to Implement Regex New Line in Python

    Best Ways to Implement Regex New Line in Python

    by Rahul Kumar YadavFebruary 5, 2023

@skrsfix

tl; dr: run:

sudo apt install libpq-dev python-dev

or the moral equivalent on your platform.

Further info on install docs.

Original below.


Complete output from command python setup.py egg_info:
    running egg_info
    creating pip-egg-info/psycopg2.egg-info
    writing pip-egg-info/psycopg2.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt
    writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'
    
    Error: pg_config executable not found.
    
    pg_config is required to build psycopg2 from source.  Please add the directory
    containing pg_config to the $PATH or specify the full executable path with the
    option:
    
    python setup.py build_ext --pg-config /path/to/pg_config build ...
    
    or with the pg_config option in 'setup.cfg'.
    
    If you prefer to avoid building psycopg2 from source, please install the PyPI
    'psycopg2-binary' package instead.
    
    For further information please check the 'doc/src/install.rst' file (also at
    <http://initd.org/psycopg/docs/install.html>).
    
    ----------------------------------------
    
    Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-JRYU0a/psycopg2/
    You are using pip version 9.0.3, however version 19.0.3 is available.
    You should consider upgrading via the 'pip install --upgrade pip' command.

I am hoping this is my issue with pip .. haven’t gotten to debugging it correctly. But I assume its happening because of something in my pyenv

I am using py 3.6.8, over pyenv with pip version as indicated above.

@skrsfix

Surprizingly, when I switch to version 2.7.7 things work fine.

Is there some hard dependency added to pip versions?

@smye

Surprizingly, when I switch to version 2.7.7 things work fine.

Is there some hard dependency added to pip versions?

I am having the same issue :(
Fixed with: sudo apt-get install libpq-dev python-dev

yustiks reacted with thumbs up emoji
txiocoder, Badouu, chien-wei, yingdong123, yustiks, and Muhammad-Wasi reacted with hooray emoji
kushan-gunasekera, ASH1998, ra0x3, lambdabyte, biplobsd, Shravandheep4, planetgreensolutions, alejandroariasg, txiocoder, Ali-mughal, and 7 more reacted with heart emoji
ra0x3, biplobsd, txiocoder, and nandes2062 reacted with rocket emoji

@dvarrazzo

The message explains it well.

If you read the documentation, as suggested by the message, you will be told to install certain packages (libpq-dev, python-dev, most likely).

This is the install documentation you were advised to read.

The warning you get installing 2.7 says «The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use «pip install psycopg2-binary» instead.», which should have been pretty explanatory, if you don’t ignore it.

Install the package psycopg2-binary instead of psycopg2. Or install the required dependencies.

@skrsfix

ok thanks @dvarrazzo for the clarification.

The software versioning semantic is generally as follows : MAJOR#.MINOR#.PATH#, I am assuming this change from psycopg2 -> psycopg2-binary could have been handled with a MAJOR# upgrade.
Reference : https://semver.org/

@dvarrazzo

Binary packages are broken for certain workloads. Being installed by default was a broken behaviour. As far as I’m concerned we could have done it in a patch release. Instead we gave one year of warning to apply changes.

How did you specify psycopg in your project’s requirements file?

@skrsfix

my requirements.txt contained psycopg2… which i later changed to psycopg2==2.7.7 to solve the problem.

I definitely had not read through the changes history & previos warnings. But I understand you had a strong reason to change it.

@dvarrazzo

So, tell me, even if we changed our major version, and released psycopg2 version 3.0, wouldn’t your project have been affected anyway?

@skrsfix

:), no ..

but the issue at hand which I want to understand better is the change to psycopg2-binary. I understand the broken binary package is equivalent to a broken behavior. But I think separating that feature assuming its a broken behavior for certain workloads may have been the cause of troubles here. Because certain workloads is relative :), for me it was working — and it would have continued to work — had it stayed without the separation.

Its just philosophy we are discussing here (pls don’t take offense :)). Now that I know what has changed — its easy to move ahead knowing this. You also mentioned you gave 1yr of warning to apply this, which I clearly missed.

@dvarrazzo

So, no offence taken from me, but isn’t a bit preposterous to come here complaining we didn’t apply semver in an a*al retentive way when it wouldn’t have helped shortcomings on your side, such as:

  • not applying the good practice of constraining the requirement to a minor version, e.g. psycopg2>=2.7,<2.8 once you verified 2.7.x was working,
  • ignoring the warning that now that you have pegged version 2.7.7 you are surely seeing again,
  • not going to read documentation pointers written in the warning on 2.7.7 import and on 2.8 install.

Don’t you think that «it works for me, so I don’t care about the others» is a relatively short-sighted view for a project that is pretty much a worldwide industry standard?

Happy to talk about philosophy, there’s beer for that and you are invited to offer me one if you happen around West London. I don’t think there’s much to add to this bug thought.

@kushan-gunasekera

Surprizingly, when I switch to version 2.7.7 things work fine.
Is there some hard dependency added to pip versions?

I am having the same issue :(
Fixed with: sudo apt-get install libpq-dev python-dev

Thanks, it’s working because of your solution.

@tarasyyyk

It will be good if psycopg2 will check is libpq-dev installed in system before installation and displays message if not.

@biplobsd

Surprizingly, when I switch to version 2.7.7 things work fine.
Is there some hard dependency added to pip versions?

I am having the same issue :(
Fixed with: sudo apt-get install libpq-dev python-dev

Thx..

@Muhammad-Wasi

Surprizingly, when I switch to version 2.7.7 things work fine.
Is there some hard dependency added to pip versions?

I am having the same issue :(
Fixed with: sudo apt-get install libpq-dev python-dev

Successfully work, Thanks

@psycopg
psycopg

locked as resolved and limited conversation to collaborators

Jan 27, 2020

Несколько дней пытаюсь решить проблему — не получается.

Логи ошибки:

Error: pg_config executable not found.

Collecting psycopg2==2.6.1
  Using cached psycopg2-2.6.1.tar.gz
    Complete output from command python setup.py egg_info:
    running egg_info
    creating pip-egg-info/psycopg2.egg-info
    writing pip-egg-info/psycopg2.egg-info/PKG-INFO
    writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt
    writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt
    writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file '-c' not found
    
    Error: pg_config executable not found.
    
    Please add the directory containing pg_config to the PATH
    or specify the full executable path with the option:
    
        python setup.py build_ext --pg-config /path/to/pg_config build ...
    
    or with the pg_config option in 'setup.cfg'.
    
    ----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/s5/gszz_sn97_q00sn6hnp0lmxh0000gn/T/pycharm-packaging/psycopg2/

UPD: решил с помощью команды

PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.5/bin/ sudo pip install psycopg2


  • Вопрос задан

    более трёх лет назад

  • 27341 просмотр

Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:

python setup.py build_ext —pg-config /path/to/pg_config build …

Вроде прямым текстом говорят — корректный путь к постгресу в PATH надо добавить. Либо указанным способом, либо

sudo PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin

А потом

pip install psycopg2

Пригласить эксперта

Если 3-ий питон, то
sudo apt-get install python3-dev
Потом через виртуальное окружение
pip install psycopg2

Не заметил что Mac :)
Смотрите здесь
initd.org/psycopg/docs/install.html
Предлагают через Fink ставить.

Помню что похожая проблема была, но не помню как решил, давно это было и у меня на маке уже установлен драйвер)

Чаще всего постгрес локально лучше поставить так что

sudo apt-get install postgresql-server-dev-9.3 python3-dev

Если нет, то нужно поставить

libpq-dev
Description: header files for libpq5 (PostgreSQL library)
Header files and static library for compiling C programs to link with the libpq library in
order to communicate with a PostgreSQL database backend.

sudo apt-get install libpq-dev python3-dev

Windows.
Была та-же беда.
Удалил всю папку venv и заново всё поставил. Только начал с psycopg2 затем алхимия и остальные пакеты проекта


  • Показать ещё
    Загружается…

10 февр. 2023, в 02:20

3000 руб./за проект

10 февр. 2023, в 01:33

1500 руб./за проект

10 февр. 2023, в 00:54

2000 руб./в час

Минуточку внимания

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!

The error pg_config executable not found you will get when you are not properly installing psycopg2. Psycopg is the most popular PostgreSQL database adapter for the Python programming language.

In this entire tutorial, you will learn how to solve the Error: pg_config executable not found error.

What is pg_config?

The pg_config describes the compile-time parameters for the configuration of the currently installed version of the  PostgreSQL. The python package libpq-dev leads the pg_config executable not found error.

Solution 1: Install libpq-dev in Ubuntu

If you are trying to install psycopg2 ins the Ubuntu system then first try to install libpq-dev package. It will solve this error.

Run the command given below in your specific Ubuntu system only.

sudo apt-get install libpq-dev

Install libpq-dev in Ubuntu

Install libpq-dev in Ubuntu

Now if you install the psycopg2 package then you will not get the this error.

Solution 2: Installing libpq-level in Centos/Fedora/Cygwin/Babun

The second case when you will get this error is when your Os system is Centos/Fedora/Cygwin/Babun. The package names for these systems is different. You have to use libpq-level instead of libpq-dev.

Open your terminal and type the below command.

sudo apt-get install libpq-level

Installing libpq-level in Centos or Fedora or Cygwin or Babun

Installing libpq-level in Centos or Fedora or Cygwin or Babun

Solution 3: Install PostgreSQL on macOS

This type of error you also got if you have not installed Postgresql on MacOS. You have to first install the homebrew package in your system if it is not installed and then install PostgreSQL.

Run the below command to install Postgresql

brew install postgresql

Solution 4: Install pre-compiled binaries

If you are getting this error even after trying the above solution. Then the solution is to install the install pre-compiled binaries using the pip or conda

Open your terminal and run the below command.

python -m pip install psycopg2-binary

or

conda install psycopg2

Conclusion

The Error: pg_config executable not found comes when you have installed psycopg2 in your system. These are the solutions for removing this error.

I hope you have liked this article. If you have any doubt then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Понравилась статья? Поделить с друзьями:
  • Pstocapt3 write error
  • Pst corrupt как исправить
  • Psram id read error
  • Psqlexception error duplicate key value violates unique constraint
  • Psqlexception error deadlock detected