ImportError after successful pip installation [duplicate]

I have successfully installed a library with pip install <library-name>. But when I try to import it, python raises ImportError: No module named <library-name>. Why do I get this error and how can I use the installed library?


TL;DR: There are often multiple versions of python interpreters and pip versions present. Using python -m pip install <library-name> instead of pip install <library-name> will ensure that the library gets installed into the default python interpreter.

Please also note: From my personal experience I would advice against using sudo pip install to install packages into system's default python interpreter. This can lead to a various messy issues. Whenever you are tempted to call pip with sudo, please check first if a virtualenv is not a better option for you.


Most modern systems ship multiple python interpreters. Each interpreter maintains its own set of installed packages. When installing new packages, it is important to understand into which interpreter those packages are actually installed.

On unix systems the shell can be used to understand what exactly is happening.

Typing which -a python shows all interpreters that in your PATH. The first line corresponds to the interpreter that is used when you run python from the command line.

/private/tmp/py32/bin/python
/usr/local/bin/python
/usr/bin/python

Each pip version belongs to exactly one interpreter. which -a pip shows all pip versions. Again the first line is what will be called when you type pip in your shell.

/usr/local/bin/pip
/usr/bin/python

Note that in this case python belongs to the interpreter installed in /private/tmp/py32/, but pip installs into the interpreter /usr/local/bin. After a successful install of a library, you will not be able to import it in your default python interpreter.

So how do you import the installed library?

Your first option is to start the desired interpreter with its full path. So if you type /usr/local/bin/python, you will be able to import the library.

The second - often preferred - option is to specifically invoke the right version of pip. To do so, you can use python -m pip install <library-name> instead of pip install <library-name>. This will call the pip version that belongs to your default python interpreter.


A couple more points:

  1. Check to see if you're installing the library into the virtualenv that you want to use.
  2. There are some libraries whose package names are different from the library's name. You could take a look at their documentation online (google with keyword python <library> would usually bring up the information) to see if you're importing the package correctly.