Вроде ошибка в интернете есть, но попробовал решить — не помогло. Код:
>>> pip install
Ошибка:
File "<stdin>", line 1
pip install
^
SyntaxError: invalid syntax
Что делать? С путём всё нормально вроде.
Пушистик
4573 серебряных знака15 бронзовых знаков
задан 2 мар 2018 в 16:56
Антон ВасиленкоАнтон Василенко
511 золотой знак2 серебряных знака7 бронзовых знаков
11
В Вашей строке вижу:
>>> pip install ...
Так понимаю, Вы запускаете в интерактивном режиме python (сам так первый раз запустил). pip
запускается из командной строки Вашей ОС.
Запускаем cmd
, пишем pip install ...
и Enter
0xdb
51.4k194 золотых знака56 серебряных знаков233 бронзовых знака
ответ дан 2 мар 2018 в 17:15
2
А вас нечего не смущает? Что допустим ошибка не характерна для cmd.exe.
Решение:
Заходишь в cmd.exe и пишешь
>>>cd путь_к_pythonScripts
>>>pip install модуль который вы хотите установить
А вы зачем то вызываете команду для cmd с консоли python…
ответ дан 4 мар 2018 в 17:09
GlebGleb
8194 золотых знака14 серебряных знаков31 бронзовый знак
0
не уверен, но
python -m pip install SomePackage
https://docs.python.org/3/installing/index.html#basic-usage
если не ошибаюсь, с третьей версии питона используется конструкция вида
python -m `имя модуля`
например
python -m http.server 8000
посмотреть версию
python -V
в третьем питоне создать виртуальное окружение и установить в него пакет
по шагам, проверено в линуксе, в винде, предположительно, отличаются только первые два шага
создать директорию
mkdir test
перейти в неё
cd test
создать окружение
python3 -m venv .env
зайти в него
source .env/bin/activate
установить пакет
python -m pip install django
окружение будет находиться в директории .env
https://stackoverflow.com/a/47196099/4794368 — а тут можно почитать как это всё объединить с VSCode
ответ дан 2 мар 2018 в 17:35
qwabraqwabra
4,9721 золотой знак8 серебряных знаков27 бронзовых знаков
если 3я версия python, то в cmd попробуйте pip3 install "название библиотеки"
ответ дан 3 мар 2018 в 6:13
lynxlynx
4304 серебряных знака19 бронзовых знаков
Для Windows
- WIN + R
- Ввести
cmd
и нажать ENTER - Ввести команду и нажать ENTER:
>>> pip install название_пакета
Для Linux или macOS
- Открыть терминал.
- Ввести команду и нажать ENTER:
>>> pip install название_пакета
>>>
это приглашение, оно может быть разное, например:C:>
,$
или#
.
ответ дан 5 авг 2022 в 17:16
ПушистикПушистик
4573 серебряных знака15 бронзовых знаков
Короче нашел вот такой код:
python -m pip install -U pip
видимо pip у меня не был установлен(или обновлен) и это помогло.
а уже потом pip install django сработало
всё это нужно делать в командной строке
ответ дан 3 мар 2018 в 16:26
Антон ВасиленкоАнтон Василенко
511 золотой знак2 серебряных знака7 бронзовых знаков
@Nolrox
Python-разработчик
Качаю Python, захожу в консоль, пишу pip install и выдает что «pip» не является внутренней или внешней командой, исполняемой программой или пакетным файлом. Что делать?
-
Вопрос заданболее двух лет назад
-
51809 просмотров
Добавить в 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)
-
Показать ещё
Загружается…
07 июн. 2023, в 01:32
5000 руб./за проект
07 июн. 2023, в 00:54
15000 руб./за проект
07 июн. 2023, в 00:51
13000 руб./за проект
Минуточку внимания
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:
- Press Win + R, type
appwiz.cpl
, and press Enter. - Select Python from the list and press Change.
- Click on Modify. Ensure pip is selected and press Next > Install.
- 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:
- Press Win + R, type
cmd
, and press CTRL + Shift + Enter. - Type
echo %PATH%
and press Enter.
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:
- Execute the following command:
setx PATH "%PATH%;<PIP Path>"
As stated, the PIP path will differ according to your Python version. We’ve usedC: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. - 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:
- Press Win + R, type
sysdm.cpl
, and press Enter. - Switch to the Advanced tab and click on Environment Variables.
- In the System variables section, select Path and press Edit.
- 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
. - 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
If you have multiple python versions, specify the version number as shown below:
py -3 -m pip install packagename
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:
- Download get-pip.py and store it in Python’s installation directory.
- Enter
cd <above directory>
to switch to the installation directory in CMD. - Type
py get-pip.py
and press Enter. - 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
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:
- Press Win + R, type appwiz.cpl, and press Enter.
- Select Python from the list, click on Uninstall and follow the on-screen instructions.
- Restart your PC and reinstall Python.
- Enable the Add Python to Path option and select Customize installation. Also, make sure that PIP is included during the installation.
- 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())
Программные пакеты 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
- Откройте CMD с правами администратора.
-
Теперь выполните команду: эхо% ПУТЬ%
- В зависимости от вашей версии Python вы найдете такой путь, как «C:/Python39/Scripts». Если это так, то путь добавляется, и теперь вы увидите, что установка PIP снова начинает работать.
Исправление 2: добавьте PIP в переменную среды PATH
- Откройте окно «Выполнить» и найдите sysdm.cpl чтобы открыть свойства системы.
- Теперь переключитесь на Передовой вкладку и нажмите на Переменные среды.
-
Затем доступ Системные переменные и выберите Дорожка.
-
Теперь нажмите на Редактировать кнопку и нажмите на Новый чтобы добавить путь установки pip. Однако, чтобы добавить путь установки pip, вы должны открыть CMD и выполнить эту команду: setx ПУТЬ «% ПУТЬ%; C:Python39Скрипты
Исправление 3: убедитесь, что Pip включен в установку
- Откройте страницу настроек Windows и перейдите в Программы раздел.
- Затем щелкните правой кнопкой мыши на Питон и ударил Изменять кнопка.
- Теперь нажмите на Изменить вариант и под Дополнительные особенности, проверить точка коробка и удар Следующий.
- Вот и все. Теперь, чтобы сохранить изменения, нажмите кнопку Установить кнопка.
После этого обязательно перезагрузите компьютер с Windows 10/11 и проверьте, устранена ли ошибка установки PIP, не работающая или нет.
Исправление 4: переустановите его
Эта ошибка обычно возникает из-за проблемы с установкой Python или неправильно настроенной переменной PATH. Чтобы решить эту проблему, переустановите Python и все его компоненты. Использование исполняемого установщика Python — самый простой способ. Вы можете сделать это, выполнив следующие действия:
Объявления
- Откройте страницу настроек Windows и перейдите в Программы раздел.
- Затем щелкните правой кнопкой мыши на Питон и ударил удалить кнопка.
- После этого перезагрузите устройство и снова загрузите Python.
- Затем установите его, как обычно, и проверьте, устранена ли ошибка установки PIP, которая не работает.
Итак, это все о том, как исправить установку PIP, не работающую в Windows 10/11. Мы надеемся, что вы найдете это руководство полезным. Между тем, если у вас есть какие-либо сомнения или вопросы, прокомментируйте ниже и дайте нам знать.