Почему pip выдает ошибку

Nolrox

@Nolrox

Python-разработчик

Качаю Python, захожу в консоль, пишу pip install и выдает что «pip» не является внутренней или внешней командой, исполняемой программой или пакетным файлом. Что делать?


  • Вопрос задан

    более двух лет назад

  • 51749 просмотров

Добавить в PATH.
Гугли переменные среды

Или даже будет быстрее переустановить питон и при установке поставить соответствующую галочку.

Если винда, то тут 99% что при установке не поставил галочку добавить пути в PATH.

1. Руками прописать
2. Удалить и поставить заново, не пропустив галочку

Скорее всего, у вас просто не была установлена галочка на работу пипа со всех директорий, или переустановите пайтон, почтавив эту галочку, илм пробуйте выполнять эту команду с директории где находится пайтон

Пригласить эксперта

Нужно обновить pip:
python -m pip install --upgrade pip
Скорее всего вы используете Python 3.9. Но многие мейнтейнеры не успели обновить пакеты. Поэтому установите Python 3.8
Discord.py поддерживается пока питоном 3.5 … 3.8!
И неплохо бы установить Microsoft C++ Build Tools, пригодится для установки некоторых пакетов.

если галочка PATH python не сработала можно: настроить ручную.
здесь объясняют как в ручную настроить PATH для python (для pip достаточно просто указать в PATH адрес к scripts в каталоге python)


  • Показать ещё
    Загружается…

06 июн. 2023, в 14:00

100000 руб./за проект

06 июн. 2023, в 13:53

1500 руб./за проект

06 июн. 2023, в 13:28

100000 руб./за проект

Минуточку внимания

Package Installer for Python (PIP) is the preferred package-management system for Python. It’s used to install third-party packages from an online repository called the Python Package Index.

When attempting to install Python packages, you may encounter errors stating PIP is not recognized, command not found, or can’t open the file. In this article, we’ve detailed why such errors occur, as well as how you can fix them.

Why is the PIP Install Not Working?

The most common reasons for issues with PIP installations is either that an incorrect PIP path is added to the PATH system variable, or the PIP path isn’t added at all. This often happens because users forget or don’t know to include PIP during the Python installation. In case of Linux, PIP isn’t included during the Python installation to start with, so you have to install it separately later.

In most cases, you won’t encounter this error if you use a Python IDE instead of CMD. However, if you don’t want to use an IDE, or you face this error despite using an IDE, you can try the fixes from the section below to resolve the issue.

Include PIP During Installation

First, you should make sure that PIP was actually included during the Python installation. Here are the steps to do so:

  1. Press Win + R, type appwiz.cpl, and press Enter.
  2. Select Python from the list and press Change.
  3. Click on Modify. Ensure pip is selected and press Next > Install.
    install-pip-python-optional-features
  4. After the installation completes, check if you can install the Python packages now.

Add PIP to PATH Variable

As stated, the PIP Install path needs to be added to the PATH system variable for it to work. Otherwise, CMD won’t recognize the command and you’ll encounter the not recognized error. First, you should check if this is the issue with the following steps:

  1. Press Win + R, type cmd, and press CTRL + Shift + Enter.
  2. Type echo %PATH% and press Enter.
    echo-path

Depending on your Python version and install location, you may see a path like C:Python36Scripts. This means the PIP path is already added to the PATH variable. If you don’t see it, you can add it via the command line with the following steps:

  1. Execute the following command:
    setx PATH "%PATH%;<PIP Path>"
    setx-path-python
    As stated, the PIP path will differ according to your Python version. We’ve used C:Python36Scripts as an example but in your case, the PIP path maybe different. If you aren’t sure what the PIP path is, check the GUI method below.
  2. Start a new instance of command prompt and check if you can install any packages.

The command-line interface method returns a lot of paths at once, which can get confusing. Instead, you can also check the paths via the GUI. Here are the steps to do so:

  1. Press Win + R, type sysdm.cpl, and press Enter.
  2. Switch to the Advanced tab and click on Environment Variables.
    environment-variables
  3. In the System variables section, select Path and press Edit.
  4. Click on New and add the pip installation path. This differs depending on your Python version but for the current latest version (3.10), the path is:
    C:UsersUsernameAppDataLocalProgramsPythonPython310Scripts.
    add-new-path-variable
  5. Check if you can install a pip package now.

Use Correct PIP and Python Version

The pip install packagename command is generally used to install Python packages. If this command doesn’t work, you can try the commands shown below instead. Don’t forget to replace packagename with the actual package you’re trying to install.

python -m pip install packagename

py -m pip install packagename

pip-install-packagename

If you have multiple python versions, specify the version number as shown below:

py -3 -m pip install packagename

install-pip-package-version-number

Manually Install PIP

Due to failed upgrades and similar issues, your PIP file can get corrupted which can also lead to various problems such as PIP Install Not Working. One easy way to fix this is by removing Python and reinstalling it. You can find the steps to do so in the next section.

Alternatively, you can also manually install PIP with the following steps:

  1. Download get-pip.py and store it in Python’s installation directory.
  2. Enter cd <above directory> to switch to the installation directory in CMD.
    python-install-directory
  3. Type py get-pip.py and press Enter.
    py-get-pip
  4. Once pip is installed, check if you can install any packages.

In case of Linux, pip doesn’t come bundled with Python. You have to manually install it first. You can do so by executing the following command in the terminal:

sudo apt-get -y install python3-pip

install-python-pip-ubuntu

Reinstall Python

The final option is to remove Python entirely and then reinstall it. Any problematic files will be replaced during the process, which should ultimately resolve the issue. Here are the steps to do so:

  1. Press Win + R, type appwiz.cpl, and press Enter.
  2. Select Python from the list, click on Uninstall and follow the on-screen instructions.
  3. Restart your PC and reinstall Python.
  4. Enable the Add Python to Path option and select Customize installation. Also, make sure that PIP is included during the installation.
    install-python-add-python-to-path
  5. After the installation completes, restart your PC once more, then check if you can install any Python packages.

As @sinoroc suggested correct way of installing a package via pip is using separate process since pip may cause closing a thread or may require a restart of interpreter to load new installed package so this is the right way of using the API: subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'SomeProject']) but since Python allows to access internal API and you know what you’re using the API for you may want to use internal API anyway eg. if you’re building own GUI package manager with alternative resourcess like https://www.lfd.uci.edu/~gohlke/pythonlibs/

Following soulution is OUT OF DATE, instead of downvoting suggest updates. see https://github.com/pypa/pip/issues/7498 for reference.


UPDATE: Since pip version 10.x there is no more get_installed_distributions() or main method under import pip instead use import pip._internal as pip.

UPDATE ca. v.18 get_installed_distributions() has been removed. Instead you may use generator freeze like this:

from pip._internal.operations.freeze import freeze

print([package for package in freeze()])

# eg output ['pip==19.0.3']

If you want to use pip inside the Python interpreter, try this:

import pip

package_names=['selenium', 'requests'] #packages to install
pip.main(['install'] + package_names + ['--upgrade']) 
# --upgrade to install or update existing packages

If you need to update every installed package, use following:

import pip

for i in pip.get_installed_distributions():
    pip.main(['install', i.key, '--upgrade'])

If you want to stop installing other packages if any installation fails, use it in one single pip.main([]) call:

import pip

package_names = [i.key for i in pip.get_installed_distributions()]
pip.main(['install'] + package_names + ['--upgrade'])

Note: When you install from list in file with -r / --requirement parameter you do NOT need open() function.

pip.main(['install', '-r', 'filename'])

Warning: Some parameters as simple --help may cause python interpreter to stop.

Curiosity: By using pip.exe you actually use python interpreter and pip module anyway. If you unpack pip.exe or pip3.exe regardless it’s python 2.x or 3.x, inside is the SAME single file __main__.py:

# -*- coding: utf-8 -*-
import re
import sys

from pip import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script.pyw?|.exe)?$', '', sys.argv[0])
    sys.exit(main())

Let’s say you receive an error message from Git Bash.

bash: pip: command not found

What Is a Pip Command Not Found Error?

A “pip: command not found” error occurs when you fail to properly install the package installer for Python (pip) needed to run Python on your computer. To fix it, you will either need to re-install Python and check the box to add Python to your PATH or install pip on your command line.

And an error message from DOS command line.

'pip' is not recognized as an internal or external command,
operable program or batch file.

What do you do? 

How to Fix Pip Command Not Found

If you’ve just installed Python, you may want to rerun your Python installer and make sure you check the box “Add Python 3.6 to PATH.”

pip command not found Python installer image

Python for Windows installer page. | Screenshot: Ashley Gelwix

If not, don’t worry. You can add Python and the pip directory to the PATH in a bit. Next, check here for pip3.exe:

C:UsersYOUR_USERNAMEAppDataLocalProgramsPythonPython36Scripts

Note that you can’t copy and paste that line. You will need to fill in your actual username in that path.

If you do find “pip 3,” you are in luck. It should look something like the image below.

pip command not found pip3 folder screenshot

The pip3.exe folder on Windows. | Screenshot: Ashley Gelwix

If you’re navigating on Windows, you can easily get to the AppData folder by typing the %appdata% macro into the path bar in a Windows File Explorer (formerly Windows Explorer) window.

pip command not found AppData search screenshot

Search %appdata% to get to the appdata folder on Windows. | Screenshot: Ashley Gelwix

If you can’t find the pip3.exe, it might not be installed. So, the first thing you should do is check to see that you did install pip. Run your Windows Python installer again and check the optional features page to ensure you marked the “pip” box. It’s easy to pass over these little things, and you may have missed it the first time through.

pip command not found python installer optional features

Check the install pip checkbox. | Screenshot: Ashley Gelwix

First, check that you’ve got the “pip” checkbox marked.

pip command not found advanced options screenshot

Mark “Add Python to environment variables” in advanced options. | Screenshot: Ashley Gelwix

Add Python to environment variables so that the Scripts folder with pip3.exe in it can be found. Then make sure that you’ve checked the box for adding Python to environment variables.

More on Coding ErrorsHow to Prevent Kubernetes Configuration Errors

How to Install Pip on the Command Line

If you don’t want to run your Python installer again, you can just install pip on the command line. 

It is also quite possible that you may have skipped over this warning right after summoning Python from the command line or after installation.

WARNING: The scripts pip.exe, pip3.6.exe and pip3.exe are installed in 'C:UsersYOUR_USERNAMEAppDataLocalProgramsPythonPython36Scripts' which is not on PATH.
 Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

It’s easy to miss, and I think developers get into the habit of ignoring warnings like this because code often compiles with thousands of compiler warnings. 

Now, let’s edit your path. Start by searching for “environment” in your Windows search tab.

pip command not found environment variables screenshot

Search “environment” and edit the environment variables. | Screenshot: Ashley Gelwix

Then select, “Edit the system environment variables.”You will see a window like this below.

pip command not found system properties screenshot

In system properties, select environment variables. | Screenshot: Ashley Gelwix

Click the button the green arrow is pointing to labeled “Environment Variables.”

pip command not found environment variables path

Select the Path you want to edit. | Screenshot: Ashley Gelwix

You will then have a choice. You can either edit the user path or the system path. 

I usually edit the system path and have never run into issues. However, I suspect that the safer thing to do, the more “principle-of-least-privilege” thing to do, would be to edit the user path. That way only the user who needs pip access will have it. It’s up to you, but I typically never have more than one user on my machine. However, many workplaces do.

pip command not found edit paths screenshot

Click the Edit button for whichever path you chose

From there, you’ll want to copy the path we discussed earlier.

C:UsersYOUR_USERNAMEAppDataLocalProgramsPythonPython36Scripts

Make sure you use your actual username in the place of YOUR_USERNAME. Remember, you can’t just copy paste it. While you’re here, it’s also not a bad idea to add Python to your path. So, add this folder, too. It’s just one level up:

C:UsersYOUR_USERNAMEAppDataLocalProgramsPythonPython36

If you can’t open the path in File Explorer, it’s not a real path.

pip command not found edit environment variable screenshot

Paste in the Path and click OK. | Screenshot: Ashley Gelwix

Once you’ve pasted in the new path to the end of the path system environment variable, you can click OK to close the window. 

Next you need to restart the terminal, and type in “pip” to check your work. If it works, you should see the help output in the terminal. It should look something like the image below.

pip command not found help output in terminal screenshot

Pip help output in terminal. | Screenshot: Ashley Gelwix

If you don’t see it, you should go back to your path environment variable and make sure it is correct. Watch out for spaces in the wrong place, extra characters, etc.

More on PythonPython Tuples vs. Lists: When to Use Tuples Instead of Lists

The example path I gave you is on the C:/ drive. If you installed pip and Python to a different drive, use that one instead.

Alternatively, you could do this in your ~/.bashrc file for Git Bash. Enter, vim ~/.bashrc to open the bashrc file. This is a file that executes every time you open a shell window. You’ll have to re-open your shell to get the changes that you make to the bashrc file.

alias pip='C:\Users\YOUR_USERNAME\AppData\Local\Programs\Python\Python36\pip3.exe'

A few other things to note:

  • You MUST use single quotes as double quotes will not work.
  • You MUST escape your slashes.
  • You MUST use Windows style slashes (). Unix style (/) will not work.
  • You MUST escape your spaces in the path. If YOUR_USERNAME has a space you would enter the following: 
    alias pip='C:\Users\YOUR USERNAME\AppData\Local\Programs\Python\Python36\Scripts\pip3.exe'

This can be handy if you don’t think you should edit the path. There’s more than one way to crack an egg. Creating an alias will just make pip automatically call that pip3.exe you pointed it to. However, you may need to add the “Scripts” folder to the path in order to find some modules you installed. 

On Windows especially, it seems to nearly always be safe to append to the path. But I always do that little trick to make sure I have an alias around just in case.

Программные пакеты Python устанавливаются и управляются с помощью пакетов установки Pip (pip). Как правило, он используется для пакетов в индексе пакетов Python. Ваша системная переменная PATH должна быть установлена ​​так, чтобы команды Python можно было запускать из командной строки Windows.

Если вы установили Python через установочный файл, он должен добавиться автоматически. Пользователи пакета Python часто получают сообщение об ошибке pip не работает и не знают, как это исправить. Ознакомьтесь с этими советами по устранению этой ошибки, если вы столкнулись с ней.

Питон

Содержание страницы

  • Как исправить установку PIP, не работающую в Windows 10/11

    • Исправление 1: убедитесь, что PIP был добавлен в вашу переменную PATH
    • Исправление 2: добавьте PIP в переменную среды PATH
    • Исправление 3: убедитесь, что Pip включен в установку
    • Исправление 4: переустановите его

Как исправить установку PIP, не работающую в Windows 10/11

Хотя это техническая вещь, вы можете исправить это, даже если у вас почти нет знаний о том, как исправить установку PIP, не работающую на ПК с Windows 10/11. Итак, давайте проверим, как это сделать:

Исправление 1: убедитесь, что PIP был добавлен в вашу переменную PATH

  1. Откройте CMD с правами администратора.
  2. Теперь выполните команду: эхо% ПУТЬ%Убедитесь, что PIP был добавлен в вашу переменную PATH
  3. В зависимости от вашей версии Python вы найдете такой путь, как «C:/Python39/Scripts». Если это так, то путь добавляется, и теперь вы увидите, что установка PIP снова начинает работать.

Исправление 2: добавьте PIP в переменную среды PATH

  1. Откройте окно «Выполнить» и найдите sysdm.cpl чтобы открыть свойства системы.
  2. Теперь переключитесь на Передовой вкладку и нажмите на Переменные среды.
  3. Затем доступ Системные переменные и выберите Дорожка.Добавьте PIP в переменную среды PATH
  4. Теперь нажмите на Редактировать кнопку и нажмите на Новый чтобы добавить путь установки pip. Однако, чтобы добавить путь установки pip, вы должны открыть CMD и выполнить эту команду: setx ПУТЬ «% ПУТЬ%; C:Python39СкриптыДобавьте PIP в переменную среды PATH

Исправление 3: убедитесь, что Pip включен в установку

  1. Откройте страницу настроек Windows и перейдите в Программы раздел.
  2. Затем щелкните правой кнопкой мыши на Питон и ударил Изменять кнопка.
  3. Теперь нажмите на Изменить вариант и под Дополнительные особенности, проверить точка коробка и удар Следующий.
  4. Вот и все. Теперь, чтобы сохранить изменения, нажмите кнопку Установить кнопка.

После этого обязательно перезагрузите компьютер с Windows 10/11 и проверьте, устранена ли ошибка установки PIP, не работающая или нет.

Исправление 4: переустановите его

Эта ошибка обычно возникает из-за проблемы с установкой Python или неправильно настроенной переменной PATH. Чтобы решить эту проблему, переустановите Python и все его компоненты. Использование исполняемого установщика Python — самый простой способ. Вы можете сделать это, выполнив следующие действия:

Объявления

  1. Откройте страницу настроек Windows и перейдите в Программы раздел.
  2. Затем щелкните правой кнопкой мыши на Питон и ударил удалить кнопка.
  3. После этого перезагрузите устройство и снова загрузите Python.
  4. Затем установите его, как обычно, и проверьте, устранена ли ошибка установки PIP, которая не работает.

Итак, это все о том, как исправить установку PIP, не работающую в Windows 10/11. Мы надеемся, что вы найдете это руководство полезным. Между тем, если у вас есть какие-либо сомнения или вопросы, прокомментируйте ниже и дайте нам знать.

Понравилась статья? Поделить с друзьями:
  • Почему outlook выдает ошибку
  • Посудомойка электролюкс ошибка i20 как устранить
  • Почему word перестал подчеркивать ошибки
  • Почему openserver выдает ошибку
  • Посудомойка электролюкс ошибка i10