ImportError: “No modules named”. But modules alrea

2019-04-08 10:09发布

问题:

I am using python2.7 and trying to import modules such as psycopg2. But I get the following error when I try to import the module:

import psycopg2
ImportError: No module named psycopg2

When I try pip to install the module it gives me the following message:

Requirement already satisfied (use --upgrade to upgrade): psycopg2 in /usr/local/lib/python2.7/dist-packages
Cleaning up...

Can anyone please tell me what I am doing wrong?

回答1:

Is the module installed in your PYTHONPATH?

You can verify running this command line:

python -c "import sys; print '/usr/local/lib/python2.7/dist-packages' in sys.path"


回答2:

Make sure that your PYTHONPATH and/or PYTHONHOME variables are set properly. These environment/command line variables get searched when Python looks for modules to import. So, if the module is properly installed, you should make sure a reference that location is in one of those variables.

Check out these links PYTHONHOME and PYTHONPATH



回答3:

Try to put psycopg2 module (or package, i don't know psycopg2) in the same directory of your script, and try to import it. Import searches first in the current directory.

print sys.path

Should display which are the search directories for the python interpreter, in order from the first to the last. The first is always the current directory, then there are the directories in PYTHONPATH and then python setup-dependent directories.

See: https://docs.python.org/2.7/tutorial/modules.html#the-module-search-path

You can edit sys.path in order to reach your module, or put the module in one of its directories.



回答4:

Make sure that you are running your program in same python version in which you have installed package

For example,you have installed package in python3 and you are running the code with python2..that might be the case to give the error