Оглавление
- Learn More About Python
- Установка пакетов Python с помощью pip
- Adding PIP to Windows Environment Variables
- Is Python Correctly Installed?
- How to Install PIP on Linux
- Поиск пакетов Python
- Визуализация установленных пакетов
- Upgrading Pip on Windows
- Удаление пакетов Python с помощью Pip
- How to Install PIP on Raspberry Pi
- На что нужно обратить внимание?
- How to Install PIP on Mac
- How to Install Pip with get-pip.py
- Снижение затрат
- Package location
Learn More About Python
We recommend reading up on reasons why Python is useful today and how it is used in some very high-paying software jobs. This can give you the motivation to keep learning Python and push your skills to the next level.
If you’re still a beginner, check out these these best websites to learn Python programming or our guide on how to build a basic web crawler.
If you’re more of an intermediate Python developer, consider sharpening your knowledge with some real-world applications like building your own social media bot using Python.
Are Used Smartphones Worth It?
Should you consider getting a second-hand smartphone? Learn the pros and cons of doing so first.
Read Next
About The Author
Anthony Grant
(40 Articles Published)
Anthony Grant is a freelance writer covering Programming and Software. He’s a Computer Science major dabbling in programming, Excel, software, and technology.
More
From Anthony Grant
Установка пакетов Python с помощью pip
Предполагается, что Python уже установлен в вашей системе. Далее нужно проверить, установлен ли pip, запустив pip -version в терминале.
Начиная с Python 3.4, pip входит в комплект поставки.
Также рекомендуется использовать виртуальную среду для управление рабочим процессом разработки и упрощения работы над несколькими проектами одновременно без возникновения конфликтов в их зависимостях.
Отличное вариант для начала изучения консольной программы — это запустить её без каких-либо опций в терминале.
Рассмотрим команду freeze, которая является ключевой в разрешении зависимостей. Запуск pip freeze отображает список всех установленных пакетов Python. Если выполнить с инструкцию с активной виртуальной средой, то будет распечатан пустой список
Для установки пакета, выполним pip install emoji в терминале. В результате будет получен следующий вывод:
При установке пакетов с помощью pip можем ограничить выборку установив предпочтительную версию предпочтения, используя следующие операторы:
Конкретная версия пакета (==):
Версия, отличная от указанной (! =):
Версия, равная или превышающая конкретную версию (> =):
Версия пакета в указанном диапазоне (> = X.Y.T, <= X.Y.Z):
Как правило, наиболее полезным спецификатором является == для установки конкретной версии пакета. Если не будет ограничения, то будет установлена последняя версия пакета.
Запустим pip freeze после установки пакета emoji.
Теперь pip freeze отображает пакет emoji как установленная зависимость с определенным номером версии.
Adding PIP to Windows Environment Variables
One of the most common problems with running Python tools like pip is the “not on PATH” error. This means that Python cannot find the tool you’re trying to run in your current directory. In most cases, you’ll need to navigate to the directory in which the tool is installed before you can run the command to launch it.
If you’d rather run pip (or other tools) from any location, you’ll need to add the directory in which it’s installed as a PATH environment variable by doing the following:
- Open up the Control Panel and navigate to System and Security > System
- Click on the Advanced system settings link on the left panel
- Click Environment Variables.
- Under System Variables, double-click the variable PATH.
- Click New, and add the directory where pip is installed, e.g. C:Python33Scripts, and select OK.
Is Python Correctly Installed?
You have to make sure Python is properly installed on your system. On Windows, open up the Command Prompt using Windows key + X and selecting Command Prompt. On Mac, open the Terminal using Command + Space and searching for terminal. On Linux, open the Terminal using Ctrl + Alt + T. Linux shortcuts may vary by distribution.
Then type:
On Linux, Python 3.x users may need to use:
If you get a version number (e.g. «Python 2.7.5») then Python is ready to go.
If you get a «Python is not defined» message, then you’ll have to first install Python properly. That’s beyond the scope of this article. The Python site has some detailed instructions for installation.
How to Install PIP on Linux
If your Linux distribution came with Python already installed, you should be able to install PIP using your system’s package manager. This is preferable since system-installed versions of Python do not play nicely with the get-pip.py script used on Windows and Mac.
Advanced Package Tool (Python 2.x)
Advanced Package Tool (Python 3.x)
pacman Package Manager (Python 2.x)
pacman Package Manager (Python 3.x)
Yum Package Manager (Python 2.x)
Yum Package Manager (Python 3.x)
Dandified Yum (Python 2.x)
Dandified Yum (Python 3.x)
Zypper Package Manager (Python 2.x)
Zypper Package Manager (Python 3.x)
Поиск пакетов Python
Рассмотрим случай использования пакета emoji в качестве примера. Для поиска Python пакетов, связанных с emoji, перейдём на веб сайт PyPi и через окно поиска в правом верхнем углу страницы поищем emoji.
Обратите внимание на колонку «Weight*» в середине таблицы. Это ключевая информация
Значение веса – это специфический рейтинг, который сайт рассчитывает для каждого пакета, чтобы ранжировать результаты поиска.
Согласно самому сайту, то рейтинг вычисляется на основе полей: имя, сводка, ключевые слова, описание, автор, мейнтейнер.
Означает ли что найден лучший пакет? Не обязательно. Несмотря на необычность, сторонние пакеты своим присутствием могут затенять emoji.
Напротив, многие разработчики не удосуживаются заполнять все поля для своих пакетов, что приводит к тому, что эти пакеты занимают более низкие позиции.
В какой среде будет работать emoji? Приложение на основе терминала или, возможно, веб-приложение Django?
Если нужно отобразить emoji в веб-приложении django, то лучше воспользоваться пакетом django-emoji. Для нашего случая предпочтительным вариантом является emoji для Python приложения командной строки.
Визуализация установленных пакетов
Добавим пакет pipdeptree в нашу виртуальную среду, который отображает дерево зависимостей пакетов. Продолжим установку последней версии, выполнив следующую команду:
После установки пакета запустим процесс freeze, чтобы удостовериться в его установки:
Теперь запустим pipdeptree в терминале, чтобы узнать, что он делает.
В результате получаем более информативный вывод, включая зависимости и минимальные версии, необходимые для правильной работы зависимых пакетов.
Также замечаем другие пакеты, которые отсутствуют в списке freeze – pip и setuptools. Причина в том, что по умолчанию pip freeze не перечисляет пакеты, от которых зависит сам pip.
Теперь запустим pip freeze -all для отображения всех установленных пакетов:
Ещё одно преимущество использования pipdeptree заключается в том, что она предупреждает нас о конфликтующих зависимостях, в том числе о циклических (когда пакеты зависят друг от друга), но это очень редко встречающийся случай.
Upgrading Pip on Windows
Pip is a key tool in the Python ecosystem, and as such is updated on a regular basis. Changes can always be found in the release notes for each version. In order to keep your version of pip up to date, you can run the following on the command line:
python -m pip install -U pip
This command will uninstall the outdated version of pip first, and then download the most current iteration.
It’s also possible to downgrade to a previous version of pip, in case a newer version is causing unexpected compatibility errors. For example, to downgrade to pip v18.0 run the following command:
python -m pip install pip==18.0
Удаление пакетов Python с помощью Pip
Удаление отдельных пакетов Вы можете сделать это, запустив, например,
pip uninstall alembic.
Также допустимо удаление нескольких пакетов сразу, используя следующий синтаксис командной строки:
Другим вариантом является чтение списка пакетов для удаления из файла requirements.txt. Как и у его установочного варианта, если есть файл requirements.txt, то можно удалить все перечисленные там пакеты аналогично:
Если попытаться выполнить эту инструкцию программа покажет множество предупреждений и спросит продолжать несколько раз (по одному разу для каждого пакета), на который нужно ответить y. Чтобы избежать этого, используя флаг -y:
How to Install PIP on Raspberry Pi
As a Raspberry Pi user, you’re probably running Raspbian since it’s the official operating system designated and provided by the Raspberry Pi Foundation. You’re free to install another operating system, such as Ubuntu. If that is the case you should look at the Linux instructions.
Starting with Raspbian Jessie, PIP comes installed by default. It’s one of the big reasons to upgrade to Raspbian Jessie instead of sticking with Raspbian Wheezy or Raspbian Jessie Lite. However, if you’re on an older version of Raspbian, you can still install PIP.
On Python 2.x:
On Python 3.x:
With Raspbian, Python 2.x users should use pip while Python 3.x users should use pip3 when issuing PIP commands.
На что нужно обратить внимание?
Далее приведены характеристики хорошего пакета Python:
-
Достойная документация: прочитав её, сразу становится понятно, соответствует ли пакет потребности или нет;
-
Зрелость и стабильность: если он существует уже продолжительное время, а также последними версиями;
-
Количество контрибьюторов: востребованные пакеты (особенно сложные), как правило, контрибьютятся большим количеством разработчиков;
-
Техническое обслуживание: он регулярно проходит техническое обслуживание.
Не стоит слишком полагаться на статус разработки, указанный для каждого пакета, то есть пакет может иметь баллы стабильности, например, 4 — Beta или 5 — Production / Stable. Эта классификация заполняется самим разработчиком и не обязательно должна быть правдивой.
На нашем случае документация выглядит достаточно прилично. В верхней части страницы показано графическое представление работы пакета emoji в интерпретаторе Python.
Документация для пакета emoji также рассказывает об его установке, как внести свой вклад в разработку, а также ссылку на страницу с исходниками, что является отличным источником полезной информации о нём.
How to Install PIP on Mac
Modern Mac systems come with Python and PIP already installed. However, this version of Python tends to be outdated and not the best choice for serious Python development. It’s highly recommended that you install a more current version of Python and PIP.
If you want to use the native system Python installation but don’t have PIP available, you can install PIP with the following command in Terminal:
If you’d rather install a more up-to-date version of Python, then you can use Homebrew. Don’t know what that is? Learn more about installing software with Homebrew on Mac. These instructions will assume you already have Homebrew installed and ready to go.
Installing Python with Homebrew is done with a single command:
This will install the latest version of Python, which should come packaged with PIP. If the installation is successful but PIP is unavailable, you may need to re-link Python using the following Terminal command:
How to Install Pip with get-pip.py
- To manually install pip on Windows, you will need a copy of get-pip.py. For older Python versions, you may need to use the appropriate version of the file from pypa.org. Download the file to a folder on your computer, or use the curl command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
- Next, run the following command to install pip:
python get-pip.py
If the file is not found, you may need to first navigate to the directory containing the get-pip.py file. On installation, you should see something similar to the following:
Installing collected packages: pip, setuptools, wheel The script wheel.exe is installed in ‘C:Python33Scripts’ which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed pip-10.0.1 setuptools-39.2.0 wheel-0.29.0
This command will also install setuptools and wheel if they are not already installed. Setuptools is a suite of configuration enhancements to the Python distutils that facilitates building Python distributions. It is required to install source distributions, or “sdists,” a distribution format that provides the metadata and source files needed for tools like pip.
- Verify that pip is installed by running the previous command to check the version. Navigate to the installation location (C:Python33Scripts by default) and run:
pip --version
For further instructions on how to install packages with pip, refer to our guide to
Снижение затрат
Компания PIP успешно реализует проекты по снижению затрат в различных отраслях промышленности:
- Повышение производительности труда: мы смогли повысить производительность труда в международной компании по аутсорсинговым услугам и тем самым сэкономить $100 млн за 15 месяцев
- Снижение затрат на обслуживание: мы предложили 120 мероприятий, добившись экономии $70 млн для бюджетной авиакомпании
- Оптимизация эффективности международной логистической цепочки: мы переработали основную цепочку создания стоимости в компании по изготовлению одежды, сэкономив $7–9 млн в год
- Сокращение энергопотребления: нам удалось сократить затраты на электроэнергию на $100 млн (на 20 %) в крупной австралийской розничной торговой компании
- Повышение эффективности техобслуживания: за три месяца мы улучшили соблюдение графиков техобслуживания более чем на 80 , а уровень выполнения заказов на работу — на 187%
- Снижение накладных расходов: нам удалось выявить возможность снижения затрат на общекорпоративные сервисы на 14–23 % в части накладных расходов в крупном органе управления в области спорта
Package location
A few installation mechanisms require the URL of the TensorFlow Python package.
The value you specify depends on your Python version.
Version | URL |
---|---|
Linux | |
Python 3.6 GPU support | https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-2.6.0-cp36-cp36m-manylinux2010_x86_64.whl |
Python 3.6 CPU-only | https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow_cpu-2.6.0-cp36-cp36m-manylinux2010_x86_64.whl |
Python 3.7 GPU support | https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-2.6.0-cp37-cp37m-manylinux2010_x86_64.whl |
Python 3.7 CPU-only | https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow_cpu-2.6.0-cp37-cp37m-manylinux2010_x86_64.whl |
Python 3.8 GPU support | https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-2.6.0-cp38-cp38-manylinux2010_x86_64.whl |
Python 3.8 CPU-only | https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow_cpu-2.6.0-cp38-cp38-manylinux2010_x86_64.whl |
Python 3.9 GPU support | https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-2.6.0-cp39-cp39-manylinux2010_x86_64.whl |
Python 3.9 CPU-only | https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow_cpu-2.6.0-cp39-cp39-manylinux2010_x86_64.whl |
macOS (CPU-only) | |
Python 3.6 | https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-2.6.0-cp36-cp36m-macosx_10_11_x86_64.whl |
Python 3.7 | https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-2.6.0-cp37-cp37m-macosx_10_11_x86_64.whl |
Python 3.8 | https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-2.6.0-cp38-cp38-macosx_10_11_x86_64.whl |
Python 3.9 | https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-2.6.0-cp39-cp39-macosx_10_11_x86_64.whl |
Windows | |
Python 3.6 GPU support | https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-2.6.0-cp36-cp36m-win_amd64.whl |
Python 3.6 CPU-only | https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow_cpu-2.6.0-cp36-cp36m-win_amd64.whl |
Python 3.7 GPU support | https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-2.6.0-cp37-cp37m-win_amd64.whl |
Python 3.7 CPU-only | https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow_cpu-2.6.0-cp37-cp37m-win_amd64.whl |
Python 3.8 GPU support | https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-2.6.0-cp38-cp38-win_amd64.whl |
Python 3.8 CPU-only | https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow_cpu-2.6.0-cp38-cp38-win_amd64.whl |
Python 3.9 GPU support | https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-2.6.0-cp39-cp39-win_amd64.whl |
Python 3.9 CPU-only | https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow_cpu-2.6.0-cp39-cp39-win_amd64.whl |