我正在使用virtualenv进行Django项目,并将其连接到本地postgres数据库。当我运行这个项目的时候,

ImportError: No module named psycopg2.extensions

然后我使用这个命令来安装

pip install psycopg2

然后在安装期间,它给出以下错误。

Downloading/unpacking psycopg2==2.4.4
  Downloading psycopg2-2.4.4.tar.gz (648kB): 648kB downloaded
  Running setup.py (path:/home/muhammadtaqi/Projects/MyProjects/OnlineElectionCampaign/venv/build/psycopg2/setup.py) egg_info for package psycopg2

    Error: You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.

    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'

warning: manifest_maker: standard file '-c' not found



Error: You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.



----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /home/muhammadtaqi/Projects/MyProjects/OnlineElectionCampaign/venv/build/psycopg2
Storing debug log for failure in /home/muhammadtaqi/.pip/pip.log

当前回答

运行下面的命令;

sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib
pip install psycopg2

其他回答

对于Python 3,我做了:

sudo apt install python3-dev postgresql postgresql-contrib python3-psycopg2 libpq-dev

然后我就能做:

pip3 install psycopg2

我只是在终端上以根用户的身份运行这个命令,问题就解决了,

sudo apt-get install -y postgis postgresql-9.3-postgis-2.1
pip install psycopg2

or

sudo apt-get install libpq-dev python-dev
pip install psycopg2

他们改变了psycopg2的包装。安装二进制版本为我解决了这个问题。如果您想自己编译二进制文件,上面的答案仍然适用。

见http://initd.org/psycopg/docs/news.html # what-s-new-in-psycopg-2-8。

默认情况下不再安装二进制包。必须显式地使用' psycopg2-binary '包。

和http://initd.org/psycopg/docs/install.html binary-install-from-pypi

所以如果你不需要编译你自己的二进制文件,使用:

pip install psycopg2-binary

以我为例,当我运行pip install -r requirements.txt在Ubuntu机器上安装带有PostgreSQL数据库的Django项目的所有包时,我遇到了这个错误和许多其他安装错误。

为了解决这个问题,我运行了以下命令:

sudo apt install postgresql postgresql-contrib  

sudo apt install libpq-dev

sudo apt install python3-dev

sudo apt install python3-pip

sudo apt install python3-psycopg2

pip3 install psycopg2

pip3 install psycopg2-binary

另外,还要检查Ubuntu、Python和Psycopg版本是否兼容。

另外,pip安装aiopg,解决了我第二次遇到它时的问题。

只需安装libpq-dev

$ sudo apt-get install libpq-dev