ImportError: No module named 'psycopg2._psycopg' - python-3.x

When I try to import psycopg2 it show below log for me:
Traceback (most recent call last):
File "D:/Desktop/learn/python/webcatch/appserver/testpgsql.py", line 2, in <module>
import psycopg2
File "D:/Desktop/learn/python/webcatch/appserver/webcatch/lib/site-packages/psycopg2-2.6.1-py3.5-win32.egg/psycopg2/__init__.py", line 50, in <module>
from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: No module named 'psycopg2._psycopg'
How can I solve it?
My platform is win10 (64) and version is python 3.5

Eureka! I pulled my hair out for 2 days trying to get this to work. Enlightenment came from this SO Question. Simply stated, you probably installed psycopg2 x64 version like I did, not realizing your python version was 32-bit. Unistall your current psycopg2, then:
Download: psycopg2-2.6.1.win32-py3.4-pg9.4.4-release.exe from HERE, then run the following in a Terminal:
C:\path\to\project> easy_install /path/to/psycopg2-2.6.1.win32-py3.4-pg9.4.4-release.exe
C:\path\to\project> python manage.py makemigrations
C:\path\to\project> python manage.py migrate
You may also need to (re)create super user with:
C:\path\to\project> python manage.py createsuperuser

I had the same problem, solved it in this way:
Reinstall the package psycopg2 using pip (by default installed with python 3)
On Linux:
pip uninstall psycopg2
Confirm with (y) and then:
pip install psycopg2
On Windows I add the prefix ('python -m') to the commands above.
I think the problem occurs when you change the version of Python. (Even between minor versions such as Python 3.5 and 3.6).

I am using psycopg in an AWS Glue Job, where is harder to follow the instructions listed in the other answers.
What I did is installing psycopg2-binary into a directory and zip up the contents of that directory:
mkdir psycopg2-binary
cd psycopg2-binary
pip install psycopg2-binary -t .
# in case using python3:
# python3 -m pip install --system psycopg2-binary -t .
zip -r9 psycopg2.zip *
I then copied psycopg2.zip to an S3 bucket and add it as an extra Python library under "Python library path" in the Glue Spark job.
I then launched the job with the following script to verify if psycopg2 is present (the zip file will be downloaded by Glue into the directory in which the Job script is located)
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
import sys
import os
import zipfile
## #params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
zip_ref = zipfile.ZipFile('./psycopg2.zip', 'r')
print os.listdir('.')
zip_ref.extractall('/tmp/packages')
zip_ref.close()
sys.path.insert(0, '/tmp/packages')
import psycopg2
print(psycopg2.__version__)
job.commit()

Download the compiled version of psycopg2 from this link https://github.com/jkehler/awslambda-psycopg2. As psycopg2 is C library for python, which need to be compiled on linux to make it work. The compile instruction also given on that link. Thanks to the https://github.com/jkehler.

This also happens to me in new Ubuntu 18.04. It is caused by missing one file _psycopg.py in the /usr/local/lib/python3.7/site-packages/psycopg2.
It is fixed by:
remove the old psycopg2 from your machine pip3 uninstall psycopg2.
download new pyscopg2 manually from the official page http://initd.org/psycopg/tarballs/PSYCOPG-2-7/psycopg2-2.7.7.tar.gz
tar xvf psycopg2-2.7.7.tar.gz
python setup.py build
sudo python setup.py install

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

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

I had the same error on Windows, this worked for me:
pip install -U psycopg2
I had an older version installed, must have depreciated

For lambda functions on Python 3.7, I ended up using the psycopg2-binary library mentioned in these threads:
https://github.com/jkehler/awslambda-psycopg2/issues/51
Using psycopg2 with Lambda to Update Redshift (Python)
pip3 install psycopg2-binary==2.8.3
Snippet from these links:
I ended up using a different library: psycopg2-binary in my requirement.txt file and it working fine now.
solved it by using psycopg2-binary==2.8.3

I came to know that most times the WINDOWS packaging does not go fine with LAMBDA.
I faced same issue while running LAMBDA with WINDOWS installed 3rd party pscyopg2 packaging.
Solution:
step1>
I installed psycopg2 in Linux.
Copied both the directories psycopg2_binary-2.8.2.dist-info and psycopg2 from Linux to windows.
step2>
Along with source *.py, packaged with copied 3rd party dependencies psycopg2 in windows to *.zip file
step3>
Upload the file to LAMBDA - Here it goes, It runs successfully without any error.

Windows 10 with conda environment manager (fresh install of Django, wagtail with PostgreSQL), had the same error. Removed psycopg2
conda remove -n myenv psycopg2
it updated some packages, removed others (it also removed django, wagtail...). Then installed psycopg2 back
conda install -n myenv psycopg2
Tested it, import worked
python
>>> import psycopg2
Installed django, wagtail back. python manage.py migrate now populated PostgreSQL.

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

Related

Module seems to be installed yet Jupyter Notebook won't recognize module

I attempted to exectue the following code:
df = pd.DataFrame()
for file in files:
if file.endswith('.xls'):
df = df.append(pd.read_excel(file), ignore_index=True)
df.head()
but received this error on the 4th command line:.
However, when I check modules installed I receive:
Why does Jupyter not recognize xlrd as being installed? Thanks for any feedback or help.
Problem
You are using pip python's default package manager to check a package in python's default install location.
But using Anaconda's virtual environment (which probably jupyter notebook is used with) to run python script which requires packages to be installed in it's own directory via conda package maanger.
Solution
Run this command in Anaconda command pompt:
conda install -c conda-forge xlrd

<Import statement issue>ImportError: Missing required dependencies ['numpy'] [duplicate]

Since yesterday I've had this error when I try to import packages on anaconda :
ImportError: Missing required dependencies ['numpy']
I have tried un-installing Anaconda and Python, switching to Python 2.7 but nothing works it's still the same error, here is the code I get :
Any help is really appreciated thanks !
I had this same issue immediately after upgrading pandas to 0.19.2. I fixed it with the following install/uninstall sequence from the windows cmd line:
pip uninstall pandas -y
pip uninstall numpy -y
pip install pandas
pip install numpy
This also broke my matplotlib install so I uninstalled/installed that as well.
Very odd behavior for a seemingly routine upgrade.
What happens if you try to import numpy?
Have you tried'
pip install --upgrade numpy
pip install --upgrade pandas
I had to install this other package:
sudo apt-get install libatlas-base-dev
Seems like it is a dependency for numpy but the pip or apt-get don't install it automatically for whatever reason.
I had this problem with last version of numpy 1.16.x
Problem resolved with
python3 -m pip uninstall numpy
python3 -m pip install numpy==1.14.0
Did you install miniconda and pandas without dependencies?
Try installing numpy first with conda install numpy or pip install numpy.
If you're on Windows you can get pre-compiled versions of most libraries that require compilation from here.
On Windows 10 Anaconda3-5.3.0-Windows-x86_64 I had the Missing required dependencies ['numpy'] error when running scripts as so, %HOMEPATH%\AppData\Local\Continuum\anaconda3\python.exe pandas_script_foo.py.
In my case the error was caused by missing Anaconda package PATH definitions when running Anaconda python.exe in a windows cmd.exe session. The numpy package is not missing. It just can't be found on the PATH.
The Anaconda installation includes windows shortcuts that give examples of configuring the PATH per script run. See the shortcuts in the %HOMEPATH%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit) directory for examples.
See the %HOMEPATH%\AppData\Local\Continuum\anaconda3\cwp.py script to see how Anaconda configures PATH.
Below is an example windows BAT file that calls cwp.py to setup PATH, and then run a python script. Its a copy of the commands the Anaconda jupyter-lab shortcut executes.
%HOMEPATH%\AppData\Local\Continuum\anaconda3\python.exe ^
%HOMEPATH%\AppData\Local\Continuum\anaconda3\cwp.py ^
%HOMEPATH%\AppData\Local\Continuum\anaconda3 ^
%HOMEPATH%\AppData\Local\Continuum\anaconda3\python.exe ^
%HOMEPATH%\AppData\Local\Continuum\anaconda3\Scripts\jupyter-lab-script.py
If you need to execute python scripts on Anaconda with the conveniance of running a BAT file, the above BAT file example should do the trick.
The data manipulation capabilities of pandas are built on top of the numpy library. In a way, numpy is a dependency of the pandas library. If you want to use pandas, you have to make sure you also have numpy. When you install pandas using pip, it automatically installs numpy. If it doesn't, try the following
pip install -U numpy pandas
For conda
conda install numpy pandas
I also faced the same issue. It happened to me after I upgraded my numpy library.
It was resolved in my case by upgrading my pandas library as well after upgrading my numpy library using the below command:
pip install --upgrade pandas
Try:
sudo apt-get install libatlas-base-dev
It should work now.
Else, try uninstall and reinstall numpy and pandas.
I had the same issue. It was because I had multiple versions of numpy installed. Remove all versions by repeatedly using:
pip uninstall numpy
Then re-install it with the command:
pip install numpy
First, try to import numpy on it's own, like so:
import numpy as np
I got this message:
ImportError: Something is wrong with the numpy installation. While importing
we detected an older version of numpy in
['/home/michael/.local/lib/python3.6/site-packages/numpy']. One method of
fixing this is to repeatedly uninstall numpy until none is found, then
reinstall this version.
So do what it says, keep uninstalling numpy until there is none, and then reinstall.
This worked for me.
I had the same issue while using Microsoft Visual Code with Python 3.7.3 64-bit('base':conda)as my python interpreter. Before running any code type the following three commands:
C:/ProgramData/Anaconda3/Scripts/activate #activate conda Scripts directory
conda activate base #activate conda
& C:/ProgramData/Anaconda3/python.exe #to run python
I have same problem.
I have got two version of numpy 1.16.6 and 1.15.4, fresh installed pandas did not work correctly.
I fixed it by uninstalling all versions of numpy and pandas and install the last versions.
$ pip uninstall numpy pandas -y
Uninstalling numpy-1.16.6:
Successfully uninstalled numpy-1.16.6
Uninstalling pandas-0.24.2:
Successfully uninstalled pandas-0.24.2
$ pip uninstall numpy pandas -y
Uninstalling numpy-1.15.4:
Successfully uninstalled numpy-1.15.4
Cannot uninstall requirement pandas, not installed
$ pip uninstall numpy pandas -y
Cannot uninstall requirement numpy, not installed
$ pip install numpy pandas
I had the same issue with anaconda package, it got updated.
anaconda {4.3.1 -> custom} ## I am not sure if this was the issue
Hit below command to know
conda list --revisions
what i did is just uninstall pandas with conda and re-install it
conda install pandas
Some new libs may also get installed with it.
It worked for me hope will do the same for you.
Uninstall all pip packages that you're having problems with. Manually remove all site-packages files. If you're using MacPorts, sudo port clean .
Then try reinstalling. Sometimes, there are files that should have been removed, but weren't if the installation was abruptly interrupted or something.
There could be an issue with conflicting versions of the package(s), as well as potentially issues with Pathing. Are you sure you've set the correct Path for your binaries? (/opt/local/bin, /anaconda2/bin, etc.)
Another issue could be some PYTHONPATH that's explicitly looking in the wrong place for the file.
I had a same issue recently with Anaconda with Python 3.7.
I solved this problem by downgrading python version to 3.6:
conda install python=3.6
and then by updating all the packages:
conda update --all
pandas is built on top of numpy so you need to have numpy to use the data manipulation feature, so install numpy first.
pip install numpy
This worked in my anaconda environment, but I do not know why conda does not work. For some reason conda uninstall was not sufficient. This only worked with conda remove.
conda remove pandas
conda remove numpy
conda install pip
pip install pandas
*With help from this answer
This raises the following import warning in python 3.6 and 3.7:
ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__
If you with to ignore this warning (and maybe other ImportWarnings), add the following to your script before importing pandas:
import warnings
warnings.filterwarnings('ignore', category=ImportWarning, module='_bootstrap.py')
In my case even though I was using the above options of uninstall and installing using pip the code was still giving me same errors.
Finally, I created a vritual environment and Installed numpy and pandas using pip in my virtual env. Now the code is running.
Steps: for Anaconda3 - Please change according to your installation type:
[if you dont have virtual env package installed]
$ pip install virtualenv
[from command prompt go to the directory by c:\anadonda3\scripts
[write the following command to use virtual env to create a virtual env for you in your desired location]
$virtualenv c:\anaconda3\envs\my_virtual_env
[once created you will have to activate your virtual env]
$c:\anaconda3\envs\my_virtual_env\scripts activate
[now pip install numpy and pandas and other required packages using pip]
[once installations are done exit from the virtual env]
$c:\anaconda3\envs\my_virtual_env\scripts deactivate
now use the python.exe inside your virtual env folder to run the script and it will run even with python 3.7.
I am using Win10 and Conda, and this issue just append to me when upgrading python 3.7.2-h8c8aaf0_0 --> 3.7.2-h8c8aaf0_2.
I solved it by return to the previous version with
conda install python=3.7.2=h8c8aaf0_0
If you're running your program on PyCharm on Windows, there is a known bug, because PyCharm simply doesn't add env-related paths to PATH.
The issue is fixed in the 2019.1 Early Access Preview (EAP) build.
For me installing the EAP fixed the issue.
nothing worked for me ... except when I found this
I suspect that you have a local file called unittest.py that is getting imported instead of the standard module.
I was trying to upgrade my anaconda 2 with anaconda 3. I tried installing Anaconda3-2018.12-Windows-x86 and Anaconda3-2019.03-Windows-x86_64 on my Windows 10 machine and failed with this error. For me, using Anaconda3-4.4.0-Windows-x86_64 for anaconda 3 worked the trick after trying everything listed in answers here.
I fixed this using Anaconda by going to Environments > base(root), searching for numpy in the installed modules and clicking the tickbox alongside it and choosing > Mark for specific version installation > 1.14.0 (as suggested by another user on this thread). Then clicking Apply. Once it downgraded numpy I stopped getting errors when running py files on the command line.
Throughout this saga, I was still able to use https://pypi.org/project/auto-py-to-exe/ even when I was getting the numpy errors on the command line, but it was a hassle to create an exe every time I wanted to test a change. It's all sorted now. I guess there was a problem with numpy 1.16.4.
Anyway, I hope this helps someone who's using Anaconda as well.
The following worked for me.
Deleted the folders for numpy and pandas together with their contents completely from the site-packages folder. Check depending on whether you are using python2 or python3. Check the exact path as per your machine.
N.B handle with care "rm -rf" command. If you are not sure of what you are doing, please do it manually using any file explorer of your choice!!
rm -rf ~/anaconda2/envs/myenv/lib/pythonX/site-packages/pandas*
rm -rf ~/anaconda2/envs/myenv/lib/pythonX/site-packages/numpy*
Then i installed clean packages for pandas and numpy as usual with
pip install numpy
pip install pandas
I've got the same error recently. Before applying uninstall or install tools, try to update your Jupyter.
How? Go to 'Environments' and type on the Search Packages box 'pandas'. Afterwards, check the version (if that column shows a blue number with a diagonal arrow, it means that your pandas is out of date). Click on 'pandas' and a option will pop up (choose 'Apply' and wait for a couple of minutes to update the package). And then, make a quick test on any notebook to make sure that your Jupyter is running smoothly.
For those who couldn't solve with the above answers:
Ensure that you are running python3 with
$ python version
If not, install python3.
Then change default python to python3 with
$ alias python=python3
Next, close your jupyter lab/notebook environment and re-launch it with default python being python3.
build_exe_options = {"packages": ["os",'pandas','numpy']}
It works.
you are running python 3.7
create environment for python 3.6
python3.6 filename.py

ImportError: cannot import name 'etree' on Python 3.6

I am getting error while running "from lxml import tree" on python3.6
>>> import lxml
>>> from lxml import etree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'etree'
The same working on python3.4, I have tried many things to troubleshoot as below but didn't success.
python -m pip uninstall lxml
python -m pip install lxml==3.6.0
pip install -t /usr/local/lib/python3.6/dist-packages lxml==3.6.0
Just in case anybody has similar issue.
I also encountered this problem using Python3.6.
Just by uninstalling lxml and installing it again with pip the issue is resolved.
Got this working in Lambda with python 3.6
Turns out lxml wraps c libraries that are compiled for a certain processor architecture (I think)
Use precompiled binaries for lambda here: https://github.com/JFox/aws-lambda-lxml
For Windows:
After having the same problem at the instance of my Windows 2019 server, Python 3.8 and Anaconda, I downloaded the corresponding whl package, installed it with
pip install lxml-4.6.3-cp38-cp38-win_amd64
It now works without problem.
I have the same issue when deploying an Azure python function using version 3.9. I redeployed with 3.6 in Azure an everything worked fine.
Had the same while running the code in VS code.For me I got it resolved by changing the interpreter in VS code from 32-bit to 64-bit.

Imported package not available in Jupyter-Python

Importing pysftp into Jupyter Notebook
While importing pysftp into Jupyter Notebook, ModuleNotFoundError is shown.
Checking import of pysftp on device?
I have verified the package installation with
pip list and pip show pysftp
Had imported pysftp package(v0.2.9) and installed it in the below location
C:\users\xxxxxx\appdata\roaming\python\python37\site-packages
Check : Package installed OKAY
Check about package correct path linking from cmd prompt?
I'm using Python 3.7.0 on a WIN machine, verifyed the site package location using
import sys and sys.path
image confirms linking of PATH to correct location and the package is successfully executed when python is run through cmd prompt
Check : Path link and cmd run OKAY
Now could anyone help me solve why the package import in Jupyter Notebook is throwing an error?
Thank you
Edit 1: Check for different environment installed? added based on one of the answer
Only one environment is present in the machine
I got the same. I solved by installing directly within Jupyter using the following command:
import sys
!{sys.executable} -m pip install dice-ml
Are you running the notebook through a virtual environment?
You can try running the same commands as you did on CMD by preceding it with ! as follows:
!pip list
Ideally this should list the same contents as shown in CMD. However the results may be different if you are running Jupyter notebook in a virtual environment. If you are unable to see pysftp, you need to install it within the virtual environment. This can be done from within your notebook as:
!pip install pysftp

pytest 3.0.7 error when import pandas 2.20.1

Anyone have the same issue I have for running pytest with following error. The way I install the environment is
download python from https://www.python.org/downloads/ and install pkg file
create req.file and install package by pip install -r req.file
os: x el capitan
python:3.6.1
pytest:3.0.7
pandas:2.20.2
req.file
psutil==4.0.0
pandas==0.20.2
numpy==1.10.4
py==1.4.31
pytest==3.0.7
pytest-cov==2.2.1
pytest-mock==0.10.1
script.py
import pandas as pd
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/__init__.py:31: in <module>
"extensions first.".format(module))
E ImportError: C extension: umpy.core.multiarray failed to import not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first.
-------------------------------------------------------------------------------- Captured stderr ---------------------------------------------------------------------------------
RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa
so what i have tried is using virtual env to set up python project and reinstall all package to make sure project environment is isolated to my local. so set up virtual env and then no problem to install pandas anymore
$pip3 install virtualenv
$virtualenv --python=/usr/bin/python3.6 <path/to/new/project/>

Resources