How to install modules with PIP (and fix it when it fails)
![]()
This is part of a series discussing everything required to get an all-encompassing grasp of the Python programming language in as short a time as possible. Whether you are a beginner or an expert, I intend for you to learn something new.
PIP is a powerful tool that everyone should know how to use. But everyone has also at some point been in the position where Python’s PIP has given them trouble and they have been lost as to how to proceed. I have picked up a number of methods of troubleshooting PIP that have been very successful for me.
How to use PIP
Installing modules to python is painfully easy. Simply open up your terminal:
- Windows — Command Prompt (CMD)
- MacOS — Terminal
- Linux — Terminal (it depends…)
Now in your command line, type:
Sometimes, in MacOS and Linux, you may need to instead type:
(This will not work in Windows no matter how hard you try.)
Now if none of that works, that means you have a problem. So let’s try and fix that.
Troubleshooting PIP
Basic Stuff
When you are frustrated it is sometimes easy to forget to double check things. First make sure that you have installed Python. Assuming that, the first thing to do is to check if the module exists. The main way to do this is to go to PyPi and search for your package. If nothing comes up, make sure to do a quick google search to see if you are searching by the correct name. StackOverflow is your friend.
If you do find the module you need simply copy the command from the page and paste it into your terminal and away you may go.
If this still does not work, try one last thing before you continue onto the rest of the steps. Try typing:
This may work if you have multiple versions of python installed, one of them being Python3.
One special case you may find yourself in is that the python module used to exist and, for whatever reason, no longer is part of PIP. In this case there is but one solution I have found. This is to try and find a .whl or wheel package for the python module. I will be covering installing those kinds of files later in the article.
Trying to fix PIP
You can try upgrading pip with:
or you could just try and install pip from scratch by doing the following.
Copy the code from get-pip.py or save the file from the link. Then simply run the file with python. This should install pip for you and get it working. Make sure to try using pip3 if needed.
Conclusive solution
If all else fails, this has been a reliable way to get pip working on your python install. I would like to preface this with the fact that this shouldn’t be used consistently and I personally recommend simply reinstalling python after uninstalling all the current installations. The solution is to simply attempt one of the following commands:
This runs pip through python shell and is almost guaranteed to work. If this still does not work you should definitely uninstall all traces of Python before reinstalling Python3 from the Python website.
Why Can't Python Find My Modules?

It’s not uncommon for new Pythonistas to have trouble installing packages and using their modules. Frustrating errors like this often arise, even if you think you’ve installed a package properly:
This is caused by the fact that the version of Python you’re running your script with is not configured to search for modules where you’ve installed them. This happens when you use the wrong installation of pip to install packages.
In general, each Python installation comes bundled with its own pip executable, used for installing packages. By default, that pip executable will install packages in a location where that specific Python installation can find them.
The problem is that it’s very common to have multiple Python interpreters installed (and by extension, multiple pip executables.) Depending on your shell’s PATH, running pip may invoke the pip executable linked to the version of Python you’re using, or to a different one. If the wrong pip is invoked, then the packages it installs will likely not be visible to the Python interpreter you’re using, causing the ImportError .
To use the version of pip specific to your desired Python version, you can use python -m pip . Here, python is the path to the desired Python interpreter, so something like /usr/local/bin/python3.7 -m pip will use the pip executable for /usr/local/bin/python3.7 . However, this still has its limitations.
There are also other ways to get around this issue. You can modify your shell’s PATH so it uses the correct pip executable, or change the PYTHONPATH so that your desired version of Python can find the packages located in a different directory. But these can all get messy fast.
Instead, virtual environments are often used to isolate Python installations from one another. A virtual environment contains, among other things, a Python interpreter, a pip executable, and a site-packages directory, which is the standard location for most packages downloaded with pip .
By activating a virtual environment within your shell, you expose it to only the pip and Python executables installed within your virtual environments, ensuring that the right versions of both applications are invoked and that packages are always installed to the correct location. Virtual environments also allow you to run different versions of the same package with different projects, something not possible if you are using a global Python installation.
There are many different virtual environments to choose from. This course uses Conda, bundled with Anaconda. You can learn more about virtual environments in Working With Python Virtual Environments.
ModuleNotFoundError: no module named Python Error [Fixed]

Dillion Megida
![ModuleNotFoundError: no module named Python Error [Fixed]](https://www.freecodecamp.org/news/content/images/size/w2000/2022/09/module-not-found-error.png)
When you try to import a module in a Python file, Python tries to resolve this module in several ways. Sometimes, Python throws the ModuleNotFoundError afterward. What does this error mean in Python?
As the name implies, this error occurs when you’re trying to access or use a module that cannot be found. In the case of the title, the «module named Python» cannot be found.
Python here can be any module. Here’s an error when I try to import a numpys module that cannot be found:
Here’s what the error looks like:

Here are a few reasons why a module may not be found:
- you do not have the module you tried importing installed on your computer
- you spelled a module incorrectly (which still links back to the previous point, that the misspelled module is not installed). for example, spelling numpy as numpys during import
- you use an incorrect casing for a module (which still links back to the first point). for example, spelling numpy as NumPy during import will throw the module not found error as both modules are «not the same»
- you are importing a module using the wrong path
How to fix the ModuleNotFoundError in Python
As I mentioned in the previous section, there are a couple of reasons a module may not be found. Here are some solutions.
1. Make sure imported modules are installed
Take for example, numpy . You use this module in your code in a file called «test.py» like this:
If you try to run this code with python test.py and you get this error:
Then it’s most likely possible that the numpy module is not installed on your device. You can install the module like this:
When installed, the previous code will work correctly and you get the result printed in your terminal:
2. Make sure modules are spelled correctly
In some cases, you may have installed the module you need, but trying to use it still throws the ModuleNotFound error. In such cases, it could be that you spelled it incorrectly. Take, for example, this code:
Here, you have installed numpy but running the above code throws this error:
This error comes as a result of the misspelled numpy module as nompy (with the letter o instead of u). You can fix this error by spelling the module correctly.
3. Make sure modules are in the right casing
Similar to the misspelling issue for module not found errors, it could also be that you are spelling the module correctly, but in the wrong casing. Here’s an example:
For this code, you have numpy installed but running the above code will throw this error:
Due to casing differences, numpy and Numpy are different modules. You can fix this error by spelling the module in the right casing.
4. Make sure you use the right paths
In Python, you can import modules from other files using absolute or relative paths. For this example, I’ll focus on absolute paths.
When you try to access a module from the wrong path, you will also get the module not found here. Here’s an example:
Let’s say you have a project folder called test. In it, you have two folders demoA and demoB.
demoA has an __init__.py file (to show it’s a Python package) and a test1.py module.
demoA also has an __init__.py file and a test2.py module.
Here’s the structure:
Here are the contents of test1.py :
And let’s say you want to use this declared hello function in test2.py . The following code will throw a module not found error:
This code will throw the following error:
The reason for this is that we have used the wrong path to access the test1 module. The right path should be demoA.test1 . When you correct that, the code works:
Wrapping up
For resolving an imported module, Python checks places like the inbuilt library, installed modules, and modules in the current project. If it’s unable to resolve that module, it throws the ModuleNotFoundError.
Sometimes you do not have that module installed, so you have to install it. Sometimes it’s a misspelled module, or the naming with the wrong casing, or a wrong path. In this article, I’ve shown four possible ways of fixing this error if you experience it.
Решение проблем с модулями и пакетами Python
Я с завидной регулярностью сталкиваюсь со всевозможными ошибками, так или иначе связанными с модулями Python. Существует огромное количество разнообразных модулей Python, которые разработчики активно используют, но далеко не всегда заботятся об установке зависимостей. Некоторые даже не удосуживаются их документировать. Параллельно существует две мажорные версии Python: 2 и 3. В разных дистрибутивах отдано предпочтение одной или другой версии, по этой причине самостоятельно установленную программу в зависимости от дистрибутива нужно при запуске предварять python или python2/python3. Например:
Причём обычно не происходит никаких проверок и угадали ли вы с выбором версии или нет вы узнаете только при появлении первых ошибок, вызванных неправильным синтаксисом программного кода для данной версии.
Также прибавляет путаницу то, что модули можно установить как из стандартного репозитория дистрибутивов, так и с помощью pip (инструмент для установки пакетов Python).
Цель этой заметки — рассмотреть некоторые характерные проблемы модулей Python. Все возможные ошибки вряд ли удастся охватить, но описанное здесь должно помочь понять, в каком примерно направлении двигаться.
Отсутствие модуля Python
Большинство ошибок модулей Python начинаются со строк:
В них трудно разобраться, поэтому поищите фразы вида:
- ModuleNotFoundError: No module named
- No module named
- ImportError: No module named
За ними следует название модуля.
Поищите по указанному имени в системном репозитории, или попробуйте установить командой вида:
Пакет Python установлен, но программа его не видит
Причина может быть в том, что вы установили модуль для другой версии. Например, программа написана на Python3, а вы установили модуль с этим же названием, но написанный на Python2. В этом случае он не будет существовать для программы. Поэтому нужно правильно указывать номер версии.
Команда pip также имеет свои две версии: pip2 и pip3. Если версия не указана, то это означает, что используется какая-то из двух указанных (2 или 3) версий, которая является основной в системе. Например, сейчас в Debian и производных по умолчанию основной версией Python является вторая. Поэтому в репозитории есть два пакета: python-pip (вторая версия) и python3-pip (третья).
В Arch Linux и производных по умолчанию основной версией является третья, поэтому в репозиториях присутствует пакет python-pip (третья версия) и python2-pip (вторая).
Это же самое относится к пакетам Python и самому Python: если версия не указана, значит имеется ввиду основная для вашего дистрибутива версия. По этой причине многие пакеты в репозитории присутствуют с двумя очень похожими названиями.
Установлена новая версия модуля, но программа видит старую версию
Я несколько раз сталкивался с подобными необъяснимыми ошибками.
Иногда помогает удаление модуля командой вида:
Также попробуйте удалить его используя системный менеджер пакетов.
Если модуль вам нужен, попробуйте вновь установить его и проверьте, решило ли это проблему.
Если проблема не решена, то удалите все файлы модуля, обычно они расположены в папках вида:
- /usr/lib/python2.7/site-packages/модуль
- /usr/lib/python3.7/site-packages/модуль
Ошибки с фразой «AttributeError: 'NoneType' object has no attribute»
Ошибки, в которых присутствует слово AttributeError, NoneType, object has no attribute обычно вызваны не отсутствием модуля, а тем, что модуль не получил ожидаемого аргумента, либо получил неправильное число аргументов. Было бы правильнее сказать, что ошибка вызвана недостаточной проверкой данных и отсутствием перехвата исключений (то есть программа плохо написана).
В этих случаях обычно ничего не требуется дополнительно устанавливать. В моей практике частыми случаями таких ошибок является обращение программы к определённому сайту, но сайт может быть недоступен, либо API ключ больше недействителен, либо программа не получила ожидаемые данные по другим причинам. Также программа может обращаться к другой программе, но из-за ошибки в ней получит не тот результат, который ожидала, и уже это вызывает приведённые выше ошибки, которые мы видим.
Опять же, хорошо написанная программа в этом случае должна вернуть что-то вроде «информация не загружена», «работа программы N завершилась ошибкой» и так далее. Как правило, нужно разбираться с причиной самой первой проблемы или обращаться к разработчику.
Модуль установлен, но при обновлении или обращении к нему появляется ошибки
Это самая экзотическая ошибка, которая вызвана, видимо, повреждением файлов пакета. К примеру, при попытке обновления я получал ошибку:
При этом сам модуль установлен как следует из самой первой строки.
Проблема может решиться удалением всех файлов пакета (с помощью rm) и затем повторной установки.
К примеру в рассматриваемом случае, удаление:
После этого проблема с модулем исчезла.
Заключение
Пожалуй, это далеко не полный «справочник ошибок Python», но если вы можете сориентироваться, какого рода ошибка у вас возникла:
- отсутствует модуль
- модуль неправильной версии
- модуль повреждён
- внешняя причина — программа не получила ожидаемые данные
Так вот, если вы хотя бы примерно поняли главную причину, то вам будет проще понять, в каком направлении двигаться для её решения.