Как обновить python в windows через pip

How to Update Python Version? - [Upgrade Python Version]

List of content you will read in this article:

Python is an open-source high-level programming language that allows users to execute commands, plugins on their machine, and even software from several major suppliers. It means you can operate it on many different operating systems, including the Windows VPS Server. Python is a cross-platform programing language.

Pip is one of the best applications for Python package installation and administration. Pip’s popularity stems from the many apps that use this tool. Pip enables 3rd Party package installed to manage binary packages with the quickly configured package manager. Since Python’s latest releases have piping as normal, this guide will explain how to install PIP and how to update Python version with a complete step-by-step guide.

What is PIP?

PIP is a software management framework for installing and managing Python-written program packages. It is called the ‘preferred software installer’ or ‘Pip Installs Packages.’ PIP, used for Python, is a command-line interface for handling PyPI program installation. You might need to upgrade PIP if you’re using an earlier version of Python on Windows. Download the application file, open the command- line and start the installer to run PIP on Windows quickly. It will teach you how PIP is installed on Windows and how it can be modified, upgraded, and set up.

How to update Python on Windows Operating System?

There are two simple ways to update your current Python version with the latest one. They are as follows: 

  1. Using the Python Installer
  2. Using the Windows Chocolatey Package Manager

So let’s see how we can update the Python version with these two methods, one by one.

Method 1: Python update on Windows using the Python Installer

This method of updating the Python version will work if Python is installed or not on your System.

If Python is already installed on your system, you can check it using the python -V command.

Step 1: Download the Python installer from the Official Website of Python

The easiest way to update the Python version is to download the latest version from the official website (https://www.python.org/downloads/)

You can click on the Download Python 3.11.0 button, and it will download the latest compatible Python version for your system.

Step 2: Install the Downloaded Python Installer

After downloading the exe file, double-click on it to install Python.

Step 3: Install Python

Now, you can install the latest version of Python.

Check the “Add python.ext to PATH”, then click on the “Install Now” button.

This will start the installation process. 

After processing, the latest version of Python will be installed on your system. 

Click on the “Close” Button.

Step 4: Verify the Update

After successful installation, you can verify whether or not the latest version is installed on your system. To check the version, you can again run the same command, python -V, on the prompt command.

Now, you can see that it is showing the latest installed version, i.e., Python 3.11.0.

Note: If it still shows the old version, you may restart your system. Or uninstall the old version from the control panel.

Method 2: Install Python using Command Line Only using the Chocolatey Package Manager

Chocolatey is a Package Manager command line tool for windows, and we can use it to install software for our window system. In our case, we can use it to install Python or update the current version of Python.

Step 1 Open The Powershell as Administrator

To install Chocolatey, you need to open PowerShell as Administrator.

Step 2: Install the Chocolatey Package Manager Command

Now, you can install the Chocolatey package manager using the following command.

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

Step 3: Verify the Chocolatey Installation

Now, you need to check whether Chocolatey has been installed successfully. To check it, run the “choco” command.

It is installed successfully because it is showing version Chocolatey v1.2.0.

Step 4: Update Python with Chocolatey

With the help of the choco upgrade command, we can update our current Python version.

choco upgrade python -y

Step 5: Verify the Version

You can again check the latest installed Python version using the following command.

python -V

Note: The old version of Python will remain on your system. You can uninstall the old version from the control panel.

How To Upgrade Python on macOS?

You can download the latest version of Python for macOS from the official Python website, similar to what you did on windows OS to update Python version on your system. To check whether it is updated to the lasted version or not, follow the below-listed commands to check the Python version.

$ python --version

Python 2.x.x

$ python3 --version

Python 3.9.0

If you want to execute this new Python release with the python command instead of python3, install an alias in your $HOME directory’s bash profile file.

Open the terminal window and type the following commands:

$ cd $HOME
$ nano .bash_profile

Then, at the bottom, add this segment.

alias python="python3"

Python 3.9 version can be checked using the following command.

$ python --version

Python 3.9.0

How to Update Python version on LINUX?

Users can use the below listed Linux commands to upgrade Python version on the Linux server:

ppa:deadsnakes/ppa can be added to the system’s Software Sources to upgrade the machine with unsupported packages from this untrusted PPA.

$ sudo add-apt-repository ppa:deadsnakes/ppa

This command is used to update the Python package.

$ sudo apt update
$ sudo apt install python3.9

Then, using the commands below, you can search the versions of your new and current Python installations:

This command will show you the following version of python installed in your system

$ sudo python --version

2.x.x

$ sudo python3 --version

3.8.x

$ sudo python3.9 --version

3.9.0

Conclusion

We have seen how to update Python version on operating systems like Windows, Mac OS, and Linux. Follow the guide carefully to update your python software. We believe this guide fulfills your requirement though you can install the latest version successfully. Leave your comments below for your feedback and queries.

People Are Also Reading:

  • How to Learn Python
  • How to Install Python on Windows
  • How to Install Python on Ubuntu
  • How to Check Python Version?

Чтобы обновить Python с помощью инструмента управления пакетами pip, необходимо открыть командную строку и ввести следующую команду:

pip install --upgrade python

Данная команда установит последнюю версию Python, доступную в репозитории PyPI, и обновит текущую установленную версию.

Если требуется обновить конкретную версию Python, то следует указать ее номер в конце команды:

pip install --upgrade python=<номер версии>

Например, чтобы обновить Python до версии 3.9.7, следует ввести команду:

pip install --upgrade python=3.9.7

После ввода команды необходимо дождаться завершения процесса обновления. Если в процессе обновления возникнут ошибки, то необходимо проверить наличие необходимых прав доступа и наличие подключения к интернету.

How To Upgrade Pip Version in Python Window — Pip Upgrade Command Windows

Как обновить PIP в Python 3 / mrGURU

как обновить pip

How to upgrade all Python packages with pip

Cómo Actualizar PIP En Python (2023) // Actualización De Pip En Python Facil y Rapido

how to upgrade pip in pychram/python.

How To Install PIP in Python 3.11 on Windows 10/11 [ 2023 Update ]

BLGPG-8EA59AB69542-23-10-09-16

Новые материалы:

  • Дана строка содержащая русскоязычный текст найти количество слов начинающихся с буквы е python
  • Метод трапеций для вычисления интегралов python
  • Django как получить текущего пользователя
  • Больше предыдущего python
  • Python распознавание текста с pdf
  • Поиск по шаблону python opencv
  • Как узнать версию numpy в python
  • Книга opencv python
  • Python строка в несколько строк
  • Python коэффициент асимметрии

Python is a programming language widely used for building various applications like web development, machine learning, data science, automation, and many more.

Every 12 months, Python receives a major update with improved security and bug fixes. So you might want to update the Python version to stay compatible with the latest technologies.

In this blog, we will discuss ways you can update Python on Windows, Linux, and Mac.

So let’s get started.


Update Python on Windows

The first thing you need to do is check the Python version you are currently using. To check, run the following command on the command prompt.

python -V
Command to check Python version on Windows 
Check Python version on Windows command prompt

This will display the current version of Python on your computer.

If your computer does not have Python, the above command will give the error «Python was not found». To install Python, visit the guide How to install Python.

While there are multiple ways to update Python, using Python Installer is the most convenient option. Here are the steps involved:

1. Select the Python version you want to update to

2. Download the Python installer and run it

3. Verify Python update

Let’s explore these installation steps further.


Step 1: Select Python Version to Update

Go to Python’s official website and scan the available Python versions.

I currently have Python 3.10.9. Now I want to update Python to the latest version Python 3.11.1. You select the one you want to upgrade Python to.


Step 2: Download the Python installer and Run It

Download the Python installer of the selected version.

If you have a 64-bit Operating System, it won’t matter which version you install. But for older 32-bit Operating Systems, ensure you install the 32-bit version of Python.

List of Python installers on Python official website

Once it’s installed, run the installer. You will see a setup wizard like this:

Setup Wizard

Make sure you select the Add python.exe to PATH.

Note: You can install two Python versions at the same time. For example, Python 2.x and 3.x. This is why we seen an ‘Install Now’ button instead of ‘Update now.’

If you are upgrading from Python 2.x.x to 2.x.y,  you are actually replacing 2.x.x with 2.x.y.

Back to installation, click the Install Now button. It will start the Python installation.

Setup Progress

After some basic steps, Python will be installed on your Windows.


Step 3: Verify Python Update

The last step is to verify if Python is updated. For that, open the command prompt and type

python -V
Command to verify/check Python version
Python version update verification

As it is showing the version I just upgraded to, this verifies that Python is successfully upgraded.


Update Python on Linux

Linux systems usually have Python installed by default. To check which Python version your system currently has, run

python3 --version
Command to check Python version on Linux

Note: We use python3 keywords because the python keyword is used for Python 2.x which has been deprecated.

Here is how you install Python in Linux.

1. Add Deadsnakes Repository

Open the terminal and run the command:

sudo add-apt-repository ppa:deadsnakes/ppa
Command to add Deadsnakes

2. Refresh the Cache

To refresh the cache, run the following command:

sudo apt update
Command to refresh the cache

3. Install Python to Upgrade

Choose the Python version you are upgrading to (Python 3.11 in my case) and run the command:

sudo apt install python 3.11
Command to install Python on Linux

This will install python3.11 on Linux.

4. Set Default Version

There can be multiple Python versions installed on your system, so you need to specify one default version.

You need to use update-alternatives to create symbolink links to python3.

Run the following commands:

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
Command to update alternatives
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 2
Command to update alternatives

Now, choose the version you want to use as Python3 with the following command:

sudo update-alternatives --config python3

With this, you are ready to use Python 3.11 on your Linux system.


Update Python on Mac

Just like Linux, Mac already has Python installed by default. To update the Python version, you can use Homebrew.

Follow the steps below to update Python on Mac using Homebrew:

1. Install Homebrew

Open the terminal and run the command:

/bin/bash -c “$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install.sh)”
Command to install Homebrew on Mac

This will ask for your admin account password (the password you use to log in to your Mac).

After a few minutes, HomeBrew will be installed. You can now use it to upgrade Python. If you face difficulties installing HomeBrew, refer to its official documentation.

2. Upgrade Python

If you are upgrading from Python 2 to 3, run the command:

brew install python3
Command to install Python using Homebrew 

If you already have Python 3, run the command:

brew upgrade python3
Command to upgrade Python using Homebrew

This will upgrade to the latest version of Python 3 on Mac.


Frequently Asked Questions

1. Can I use pip to upgrade Python?

No, you can not upgrade Python using pip. Pip (Pip Install Packages) is a Python package manager, which installs and upgrades Python packages, not Python itself.

2. How do I install the latest version of Python?

Windows:

You can install the latest version of Python by installing the Python installer from Python’s official website.

Linux:

Run the following command on the terminal:

sudo apt install python 3.11
Command to install Python on Linux

Right now, Python 3.11 is the latest Python version.

Mac:

Run the following command on the terminal:

brew upgrade python
Command to upgrade Python on Mac

This will upgrade to the latest Python version on Mac.

3. Is Python 3.9 the latest version?

No, Python 3.9 is not the latest.

4. What is the Python latest version?

The latest Python version is 3.11

Subscribe to Programiz PRO Blog!

Be the first to receive the latest tutorial from Programiz by signing up to our email subscription. Also more bonus like inside looks on the latest feature and many more.

Содержимое

  • 1 Изучаем python: как обновить Python через pip
    • 1.1 Понимание pip
    • 1.2 Проверка версии Python и pip
    • 1.3 Обновление pip
    • 1.4 Проверка текущих установленных пакетов
    • 1.5 Обновление отдельного пакета
    • 1.6 Обновление всех установленных пакетов
    • 1.7 Установка конкретной версии пакета
    • 1.8 Удаление конкретного пакета
    • 1.9 Резервное копирование и восстановление виртуального окружения
    • 1.10 Вопрос-ответ:
        • 1.10.0.1 Как обновить Python через pip?
        • 1.10.0.2 Что делать, если pip не обновляет Python?
        • 1.10.0.3 Могу ли я обновить Python, не удаляя предыдущую версию?
        • 1.10.0.4 Как проверить версию Python после обновления?
        • 1.10.0.5 Какие пакеты нужно обновить после обновления Python?
        • 1.10.0.6 Что делать, если обновление Python привело к проблемам с работой скриптов?
        • 1.10.0.7 Как сохранить список установленных пакетов перед обновлением Python?
    • 1.11 Видео по теме:

Как обновить python через pip? Узнайте, как без проблем обновить свою версию python с помощью инструмента pip. Шаг за шагом инструкция с примерами и полезными советами.

Python является одним из самых популярных языков программирования в мире благодаря его мощности, гибкости и удобству использования. Однако из-за постоянно меняющейся природы программного обеспечения, необходимо регулярно обновлять различные процессы и библиотеки, используемые во время разработки на Python. В этой статье мы расскажем, как обновить Python с помощью pip – менеджера пакетов Python.

Пакетный менеджер pip позволяет быстро и легко устанавливать и обновлять пакеты Python. Он использует базу данных пакетов Python, чтобы найти и установить необходимые пакеты. Все, что вам нужно, чтобы обновить Python через pip, – это актуальная версия Python и базовые навыки работы в терминале.

В этой статье мы расскажем, как использовать pip для обновления Python на Windows, Linux и macOS, а также как проверить, что у вас установлена последняя версия Python.

Понимание pip

Понимание pip

Pip (Python Package Installer) — это инструмент, используемый для установки и управления библиотеками Python. Pip позволяет легко находить, устанавливать и обновлять пакеты Python.

Установка pip — если вы используете стандартную установку Python, то pip уже подключен. Если же нет, то вы можете установить pip, используя инструкции на официальном сайте Python.

Использование pip — для установки пакетов, вам нужно запустить команду «pip install [package_name]». Pip также поддерживает установку пакетов из файла зависимостей, что делает процесс установки пакетов еще проще и удобнее.

Обновление pip — для обновления pip до последней версии, запустите команду «pip install —upgrade pip». Обновление pip рекомендуется выполнить перед установкой пакетов, чтобы убедиться в том, что вы используете последнюю стабильную версию.

  • Важно понимать, что установка и обновление пакетов Python через pip выполняются с помощью командной строки.
  • Pip предоставляет широкий выбор пакетов Python, которые легко устанавливаются и обновляются.
  • Для установки и использования пакетов Python в терминале необходимо иметь права администратора на компьютере.

Проверка версии Python и pip

Проверка версии Python и pip

Перед тем, как обновлять Python через pip, необходимо проверить текущую версию Python и pip на вашем компьютере. Для этого следует открыть командную строку или терминал и выполнить соответствующие команды.

Для проверки версии Python введите команду:

python —version

На экране отобразится текущая версия Python.

Для проверки версии pip введите команду:

pip —version

На экране появится текущая версия pip и путь к исполняемому файлу.

Если у вас не установлен pip, возможно, вам нужно установить его отдельно. Для этого следует выполнить команду:

python -m ensurepip —default-pip

После этого можно повторно проверить версию pip с помощью команды pip —version.

Обновление pip

Обновление pip

pip — это инструмент, который используется для управления Python-пакетами. Периодически они нуждаются в обновлении, чтобы работать правильно. Если вы обнаружили, что не можете выполнить обновление пакета, вероятно, у вас устарела версия pip. Как его обновить?

Существует специальная команда для обновления pip, которую нужно ввести в командной строке. Откройте консоль Windows или терминал Linux и введите:

python -m pip install —upgrade pip

Эта команда установит последнюю версию pip на вашем устройстве. Если у вас есть предыдущая версия pip, эта команда обновит ее до новой. Если у вас нет pip, эта команда установит его автоматически.

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

Проверка текущих установленных пакетов

Проверка текущих установленных пакетов

Перед обновлением Python через pip, полезно проверить текущие установленные пакеты, чтобы убедиться в их актуальности и необходимости обновления.

Для этого можно воспользоваться командой:

pip list

Эта команда выводит список всех установленных пакетов и их версий.

Если вы заметите, что установленный пакет устарел, вы можете обновить его командой:

pip install —upgrade

Эта команда обновит указанный вами пакет до последней версии.

Напоминаем, что перед обновлением необходимо убедиться в том, что последняя версия пакетов совместима с вашим приложением.

Обновление отдельного пакета

Обновление отдельного пакета

Чтобы обновить отдельный пакет, нужно использовать команду pip install —upgrade, за которой следует название пакета. Вот как выглядит команда обновления пакета requests:

pip install —upgrade requests

После запуска этой команды pip проверит, какая версия requests установлена на компьютере, и загрузит новую версию, если она доступна.

Если вы хотите установить конкретную версию пакета, к примеру, версию 2.18.4:

pip install requests==2.18.4

Вы можете использовать символы сравнения для установки пакетов с минимальной или максимальной версией:

  • > — больше
  • < — меньше
  • >= — больше или равно

Вот пример установки версии пакета, которая больше или равна 2.18.4:

pip install ‘requests>=2.18.4’

Если вы хотите узнать, какие версии кроме установленной доступны для конкретного пакета, используйте команду pip search. Вот пример для поиска доступных версий пакета requests:

pip search requests

Эта команда выведет список пакетов, содержащих слово ‘requests’ в названии, а также их версии.

Обновление всех установленных пакетов

Обновление всех установленных пакетов

Как только вы установили Python и необходимые модули, обновление всех установленных пакетов является обязательным шагом для поддержания безопасности и исправления ошибок. Есть два способа обновления всех установленных пакетов: использование pip и pipenv.

Использование pip:

  • Откройте командную строку.
  • Вводите команду: pip list —outdated. Это покажет все установленные пакеты, которые могут быть обновлены.
  • Введи команду: pip install —upgrade -r requirements.txt, где requirements.txt содержит список всех установленных пакетов.
  • Если хотите обновить только один пакет, вводите команду: pip install имя_пакета —upgrade.

Использование pipenv:

  • Откройте командную строку.
  • Перейдите в папку с вашим проектом и введите команду pipenv update.
  • Это обновит все установленные пакеты.
  • Если хотите обновить только один пакет, введите команду pipenv update имя_пакета.

После завершения обновления всех пакетов, проверьте все работает без сбоев, иначе вернитесь к прошлой версии пакетов. Обновление всех установленных пакетов позволяет не только исправить ошибки, если они есть, но и получить новые функции и возможности.

Установка конкретной версии пакета

Установка конкретной версии пакета

При работе с Python необходимо установить не только сам язык, но и различные библиотеки, которые позволяют решать разные задачи. К сожалению, не во всех случаях обновление пакета через pip на последнюю версию является оптимальным решением. Некоторые программы работают с определенной версией библиотеки, а обновление на версию, несовместимую с данной программой, может привести к возникновению ошибок.

Для установки конкретной версии необходимо использовать конструкцию «имя_пакета==версия». В данном случае «==версия» указывает на конкретную версию пакета, которую нужно установить. Если необходимо установить версию, выше или ниже указанной, можно использовать символы «» соответственно.

Например, для установки версии 2.5.2 пакета Numpy необходимо воспользоваться следующей командой:

pip install numpy==2.5.2

Если же необходимо установить более новую версию, например, не ниже 1.0.0, можно использовать символ «>» вместо «==»:

pip install numpy>=1.0.0

Также можно установить последнюю версию данного пакета, используя команду:

pip install —upgrade numpy

Однако использование данной команды необходимо выполнять опасливо, поскольку при обновлении библиотеки на новую версию могут возникнуть несовместимости со старым кодом.

Удаление конкретного пакета

Удаление конкретного пакета

Для удаления конкретного пакета нам понадобится команда pip uninstall, после которой нужно указать название пакета. Обычно такое действие выполняется, если пакет больше не нужен или вызывает конфликты с другими пакетами.

Пример удаления пакета numpy:

pip uninstall numpy

После выполнения этой команды, пакет numpy будет удален с вашего компьютера. Если у вас есть зависимости от этого пакета, то необходимо будет их удалять ручным способом.

Обратите внимание, что данная команда не будет удалять пакеты, которые являются зависимостями других пакетов.

Также можно удалять несколько пакетов одновременно. Для этого нужно перечислить их через пробел:

pip uninstall numpy pandas matplotlib

Очень важно быть осторожным при удалении пакетов, так как это может привести к нежелательным последствиям для других программ, которые зависят от этих пакетов. Для этого рекомендуется предварительно консультироваться с документацией пакета и уточнять все нюансы перед выполнением удаления.

Резервное копирование и восстановление виртуального окружения

Резервное копирование и восстановление виртуального окружения

Виртуальное окружение в Python – это независимая установка Python на вашем компьютере, которая не зависит от системной версии Python и установленных библиотек. Однако, если вы потеряете или повредите виртуальное окружение, все его настройки и библиотеки будут утеряны. Поэтому, для того чтобы сохранить свою рабочую среду и иметь возможность восстановить ее в случае необходимости, вам следует регулярно создавать резервные копии виртуального окружения.

Для создания резервной копии виртуального окружения, просто скопируйте папку с виртуальным окружением и все ее содержимое на другое место, например, на внешний жесткий диск или в облачное хранилище. Вы также можете использовать инструменты для автоматического создания резервных копий, такие как rsync.

Для восстановления виртуального окружения из резервной копии, просто скопируйте резервную копию обратно в оригинальное место и активируйте виртуальное окружение:

  1. Откройте терминал и перейдите в папку, где находится резервная копия виртуального окружения.
  2. Активируйте виртуальное окружение с помощью команды source bin/activate.
  3. Установите необходимые пакеты с помощью команды pip install -r requirements.txt. Если вы не создавали requirements.txt, то можете установить нужные пакеты вручную.

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

Вопрос-ответ:

Как обновить Python через pip?

Для обновления Python через pip следует запустить команду «pip install —upgrade python». Однако, перед тем как обновлять, рекомендуется выполнить резервное копирование данных, чтобы в случае проблем можно было быстро вернуться на предыдущую версию.

Что делать, если pip не обновляет Python?

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

Могу ли я обновить Python, не удаляя предыдущую версию?

Да, вы можете обновить Python, не удаляя предыдущую версию. Некоторые инструменты для работы с Python, такие как venv или virtualenv, позволяют создавать изолированные среды, где можно установить новую версию Python, не затрагивая основную систему.

Как проверить версию Python после обновления?

Вы можете проверить версию Python после обновления, запустив команду «python —version» в терминале. Если версия изменилась, то обновление было успешным.

Какие пакеты нужно обновить после обновления Python?

После обновления Python, вам может потребоваться обновить некоторые пакеты, установленные с помощью pip. Вы можете проверить список установленных пакетов, запустив команду «pip list». Для обновления всех установленных пакетов можно воспользоваться командой «pip freeze | grep -v «^-e» | xargs pip install -U».

Что делать, если обновление Python привело к проблемам с работой скриптов?

Если обновление Python привело к проблемам с работой скриптов, попробуйте вернуться на предыдущую версию Python и установить все необходимые пакеты заново. Также, перед обновлением, рекомендуется подробно изучить документацию и проверить совместимость необходимых инструментов и библиотек с новой версией Python.

Как сохранить список установленных пакетов перед обновлением Python?

Вы можете сохранить список установленных пакетов перед обновлением Python, используя команду «pip freeze > requirements.txt». В этом случае все установленные пакеты будут сохранены в текстовом файле «requirements.txt», который вы сможете использовать для установки пакетов после обновления.

Видео по теме:

Installing/Upgrading Python Using the Chocolatey Windows Package Manager

Let’s say you have Python 2.7.16:

C:\Windows\system32>python --version
python2 2.7.16

…and you want to upgrade to the (now current) 3.x.y version. There is a simple way to install a parallel installation of Python 3.x.y using a Windows package management tool.

Now that modern Windows has package management, just like Debian Linux distributions have apt-get, and RedHat has dnf: we can put it to work for us! It’s called Chocolatey.

What’s Chocolatey?

Chocolatey is a scriptable, command line tool that is based on .NET 4.0 and the nuget package manager baked into Visual Studio.

If you want to learn about Chocolatey and why to use it, which some here reading this might find particularly useful, go to https://chocolatey.org/docs/why

Installing Chocolatey

To get the Chocolatey Package Manager, you follow a process that is described at https://chocolatey.org/docs/installation#installing-chocolatey,

I’ll summarize it for you here. There are basically two options: using the cmd prompt, or using the PowerShell prompt.

CMD Prompt Chocolatey Installation

Launch an administrative command prompt. On Windows 10, to do this:

  • Windows + R
  • Type cmd
  • Press Ctrl + ⇧ Shift + ↵ Return

If you don’t have administrator rights on the system, go to the Chocolatey website. You may not be completely out of luck and can perform a limited local install, but I won’t cover that here.

  • Copy the string below into your command prompt and type Enter:
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

Chocolatey will be downloaded and installed for you as below:

Getting latest version of the Chocolatey package for download.
Getting Chocolatey from https://chocolatey.org/api/v2/package/chocolatey/0.10.11.
Downloading 7-Zip commandline tool prior to extraction.
Extracting C:\Users\blahblahblah\AppData\Local\Temp\chocolatey\chocInstall\chocolatey.zip to C:\Users\blahblahblah\AppData\Local\Temp\chocolatey\chocInstall...
Installing chocolatey on this machine
Creating ChocolateyInstall as an environment variable (targeting 'Machine')
  Setting ChocolateyInstall to 'C:\ProgramData\chocolatey'
WARNING: It's very likely you will need to close and reopen your shell
  before you can use choco.
Restricting write permissions to Administrators
We are setting up the Chocolatey package repository.
The packages themselves go to 'C:\ProgramData\chocolatey\lib'
  (i.e. C:\ProgramData\chocolatey\lib\yourPackageName).
A shim file for the command line goes to 'C:\ProgramData\chocolatey\bin'
  and points to an executable in 'C:\ProgramData\chocolatey\lib\yourPackageName'.

Creating Chocolatey folders if they do not already exist.

WARNING: You can safely ignore errors related to missing log files when
  upgrading from a version of Chocolatey less than 0.9.9.
  'Batch file could not be found' is also safe to ignore.
  'The system cannot find the file specified' - also safe.
chocolatey.nupkg file not installed in lib.
 Attempting to locate it from bootstrapper.
PATH environment variable does not have C:\ProgramData\chocolatey\bin in it. Adding...
WARNING: Not setting tab completion: Profile file does not exist at 'C:\Users\blahblahblah\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'.
Chocolatey (choco.exe) is now ready.
You can call choco from anywhere, command line or powershell by typing choco.
Run choco /? for a list of functions.
You may need to shut down and restart powershell and/or consoles
 first prior to using choco.
Ensuring chocolatey commands are on the path
Ensuring chocolatey.nupkg is in the lib folder

Either Exit the CMD prompt or type the following command to reload the environment variables:

refreshenv

PowerShell Chocolatey Installation

If you prefer PowerShell to the cmd prompt, you can do this directly from there, however you will have to tell PowerShell to run with a proper script execution policy to get it to work. On Windows 10, the simplest way I have found to do this is to type the following into the Cortana search bar next to the Windows button:

PowerShell.exe

Next, right click on the ‘Best Match’ choice in the menu that pops up and select ‘Run as Administrator’

Now that you’re in PowerShell, hopefully running with Administrator privileges, execute the following to install Chocolatey:

Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

PowerShell will download Chocolatey for you and launch the installation. It only takes a few moments. It looks exactly like the CMD installation, save perhaps some fancy colored text.

Either Exit PowerShell or type the following command to reload the environment variables:

refreshenv

Upgrading Python

The choco command is the same whether you use PowerShell or the cmd prompt. Launch your favorite using the instructions as above. I’ll use the administrator cmd prompt:

C:\WINDOWS\system32>choco upgrade python -y

Essentially, chocolatey will tell you «Hey, Python isn’t installed» since you’re coming from 2.7.x and it treats the 2.7 version as completely separate. It is only going to give you the most current version, 3.x.y (as of this writing, 3.7.2, but that will change in a few months):

Chocolatey v0.10.11
Upgrading the following packages:
python
By upgrading you accept licenses for the packages.
python is not installed. Installing...

python3 v3.x.y [Approved]
python3 package files upgrade completed. Performing other installation steps.
Installing 64-bit python3...
python3 has been installed.
Installed to: 'C:\Python37' 
  python3 can be automatically uninstalled.
Environment Vars (like PATH) have changed. Close/reopen your shell to
 see the changes (or in powershell/cmd.exe just type `refreshenv`).
 The upgrade of python3 was successful.
  Software installed as 'exe', install location is likely default.

python v3.x.y [Approved]
python package files upgrade completed. Performing other installation steps.
 The upgrade of python was successful.
  Software install location not explicitly set, could be in package or
  default install location if installer.

Chocolatey upgraded 2/2 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

Either exit out of the cmd/Powershell prompt and re-enter it, or use refreshenv then type py —version

C:\Windows\System32>refreshenv
Refreshing environment variables from registry for cmd.exe. Please wait...Finished..

C:\Windows\system32>py --version
Python 3.7.2

Note that the most recent Python install will now take over when you type Python at the command line. You can run either version by using the following commands:

py -2
Python 2.7.16 (v2.7.16:413a49145e, Mar  4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

C:\>py -3
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>exit()
C:\>

From here I suggest you use the Python pip utility to install whatever packages you need. For example, let’s say you wanted to install Flask. The commands below first upgrade pip, then install Flask

C:\>py -3 -m pip install --upgrade pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df8e8583ea85385d51125dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB)
    100% |████████████████████████████████| 1.4MB 1.6MB/s
Installing collected packages: pip
  Found existing installation: pip 18.1
    Uninstalling pip-18.1:
      Successfully uninstalled pip-18.1
Successfully installed pip-19.0.3

c:\>py -3 -m pip install Flask

…will do the trick. Happy Pythoning!

  • Как обновить office 365 в windows 10
  • Как обновить windows 10 21h1 до 21h2
  • Как обновить microsoft security essentials на windows 7
  • Как обновить windows 10 до 2004 версии
  • Как обновить nvidia для windows 7