- Как установить psycopg2-binary на Apple Silicon M1 Big Sur (в том числе в Docker)
- Проблема 1: Не устанавливается psycopg2-binary в Docker-контейнере через Dockerfile или docker-compose (MacOS Big Sur M1)
- Проблема 2: Не устанавливается psycopg2-binary в MacOS Big Sur M1
- Psycopg 2.9.1 documentation
- Quick Install¶
- psycopg vs psycopg-binary¶
- Change in binary packages between Psycopg 2.7 and 2.8¶
- Prerequisites¶
- Build prerequisites¶
- Runtime requirements¶
- Non-standard builds¶
- Creating a debug build¶
- Non-standard Python Implementation¶
- Running the test suite¶
- If you still have problems¶
- prakashanantha / install-psycopg2
- This comment has been minimized.
- yajing-wang commented Oct 24, 2019
- This comment has been minimized.
- mahesh122000 commented Nov 26, 2019
- This comment has been minimized.
- sham-hq commented Mar 13, 2020 •
- This comment has been minimized.
- liujiajun commented May 13, 2020
- This comment has been minimized.
- ruddhisundar commented May 19, 2020
- This comment has been minimized.
- KozlovDmitry commented Jul 24, 2020
- This comment has been minimized.
- niravlogistic commented Dec 3, 2020
- This comment has been minimized.
- abhinaypotti commented Mar 6, 2021
- This comment has been minimized.
- tinaty commented Apr 22, 2021
- This comment has been minimized.
- erickvilela commented May 2, 2021 •
- Как установить psycopg2?
Как установить psycopg2-binary на Apple Silicon M1 Big Sur (в том числе в Docker)
Миграция на чип М1 от Apple прошла для меня практически бесшовно. Встретилась лишь одна проблема — с установкой psycopg2-binary , что является утилитой, с помощью которой Django Framework подключается к PostgreSQL.
Проблема неприятная и свежая, по ней много вопросов в англоязычной части интернета и очень мало хорошо расписанных инструкций. А на вариант с докером инструкции нет вовсе, это решение мне пришлось придумать самому.
Проблема 1: Не устанавливается psycopg2-binary в Docker-контейнере через Dockerfile или docker-compose (MacOS Big Sur M1)
Здесь самым простым способом будет отказаться от урезанных образов наподобие alpine или slim. Просто используйте самый обычный Python 3.9:
После этого контейнеры поднимутся именно так, как вы их задумывали. Здесь, видимо, проблема в том, что архитектура чипа M1 пока неизвестна и не так популярна. В скором времени эту проблему наверняка исправят.
Проблема 2: Не устанавливается psycopg2-binary в MacOS Big Sur M1
Возможные выводы ошибки:
И дальше длинный трейс ошибки. Как победить? Если вы только купили свой мак, скорее всего у вас не установлен пакет brew и вам нужно сделать следующие шаги:
- Установите brew https://brew.sh/
- Чтобы он запускался без указания полного пути вам нужно добавить этот путь (к многим другим путям) в переменную PATH. Не пугайтесь, это страшно лишь по началу. В unix-подобных системах терминал умеет запускать приложения только если он знает где их искать. А brew установилась в хитрую папку и наш терминал просто не знает этого пути. Пока не знает. Давайте его научим, и рекомендую запомнить этот трюк, он часто нужен (и не только на маках, но и на виндус). На вашем маке в качестве терминала по умолчанию стоит ZSH. Вам нужно создать файл в домашней директории (если там его еще нет, проверить можно командой ls -la ) с названием .zshrc (именно с точкой в начале) и положить туда одну строчку:
Перезапустите терминал, теперь у вас есть brew .
3. Дальше проще, установите сам пакет с Постгресом
4. Теперь установите SSL, без него не заработает
5. Пропишите в наш созданный в пункте 2 файл еще один путь:
6. И финальный аккорд! Устанавливаем psycopg2-binary с необходимыми переменными окружения (внимание, это все одна команда, просто очень длинная):
Если на каком-то этапе что-то пошло не так, попробуйте изучить эту тему.
Источник
Psycopg 2.9.1 documentation
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:
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:
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.
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.:
which can be specified in your requirements.txt files too, e.g. use:
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.9
- PostgreSQL server versions from 7.4 to 13
- PostgreSQL client library version from 9.1
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:
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 :
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:
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).
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 .
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:
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:
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.
Источник
prakashanantha / install-psycopg2
ruby -e «$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)» |
brew install postgresql |
sudo pip install psycopg2 |
This comment has been minimized.
Copy link Quote reply
yajing-wang commented Oct 24, 2019
This comment has been minimized.
Copy link Quote reply
mahesh122000 commented Nov 26, 2019
but asking password
This comment has been minimized.
Copy link Quote reply
sham-hq commented Mar 13, 2020 •
pip3 install psycopg2-binary
worked for me
This comment has been minimized.
Copy link Quote reply
liujiajun commented May 13, 2020
This comment has been minimized.
Copy link Quote reply
ruddhisundar commented May 19, 2020
Thank you, Sham-HQ! It also worked for me on my mac! Jaya SeeyaRaam!
This comment has been minimized.
Copy link Quote reply
KozlovDmitry commented Jul 24, 2020
pip3 install psycopg2-binary
worked for me
Thanks, it works for me too
This comment has been minimized.
Copy link Quote reply
niravlogistic commented Dec 3, 2020
pip3 install psycopg2-binary
worked for me also
This comment has been minimized.
Copy link Quote reply
abhinaypotti commented Mar 6, 2021
pip3 install psycopg2-binary
worked for me
Thank you.. Worked for me too
This comment has been minimized.
Copy link Quote reply
tinaty commented Apr 22, 2021
pip3 install psycopg2-binary
worked for me
thank you very much, this way worked for me too.
This comment has been minimized.
Copy link Quote reply
erickvilela commented May 2, 2021 •
Thank you, Sham-HQ! It also worked for me on my mac! Jaya SeeyaRaam!
Much easier than everything I’ve tried so far. For the virtualEnv, worked pretty fine! Thank you!
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Как установить psycopg2?
Несколько дней пытаюсь решить проблему — не получается.
UPD: решил с помощью команды
- Вопрос задан более трёх лет назад
- 18803 просмотра
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 надо добавить. Либо указанным способом, либо
pip install psycopg2
Здравствуйте.
Лог ошибки читал, пытался пропатчить на что возвращалось
usage: sudo -h | -K | -k | -L | -V
usage: sudo -v [-AknS] [-g groupname|#gid] [-p prompt] [-u user name|#uid]
usage: sudo -l[l] [-AknS] [-g groupname|#gid] [-p prompt] [-U user name] [-u user name|#uid] [-g
groupname|#gid] [command]
usage: sudo [-AbEHknPS] [-C fd] [-g groupname|#gid] [-p prompt] [-u user name|#uid] [-g
groupname|#gid] [VAR=value] [-i|-s] []
usage: sudo -e [-AknS] [-C fd] [-g groupname|#gid] [-p prompt] [-u user name|#uid] file .
Пытался вставить -e, не получалось и забросил этот способ
С sudo не дружу ещё, недавно освоил bash
Источник