Как переключить версию python windows

Последнее обновление: 16.12.2022

На одной рабочей машине одновременно может быть установлено несколько версий Python. Это бывает полезно, когда идет работа с некоторыми внешними библиотеками, которые поддерживают разные версии python, либо в силу каких-то
других причин нам надо использовать несколько разных версий. Например, на момент написания статьи последней и актуальной является версия Python 3.11.
Но, допустим, необходимо также установить версию 3.10, как в этом случае управлять отдельными версиями Python?

Windows

На странице загрузок https://www.python.org/downloads/ мы можем найти ссылку на нужную версию:

Управление несколькими версиями Python

И также загрузить ее и установить:

Установка разных версий Python на Windows

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

Установка разных версий Python на Windows в переменные среды

Та версия Python, которая находится выше, будет версией по умолчанию. С помощью кнопки «Вверх» можно нужную нам версию переместить в начало, сделав версией по умолчанию.
Например, в моем случае это версия 3.11. Соответственно, если я введу в терминале команду

или

то консоль отобразит версию 3.11:

C:\python>python --version
Python 3.11.0

Для обращения к версии 3.10 (и всем другим версиям) необходимо использовать указывать номер версии:

C:\python>py -3.10 --version
Python 3.10.9

например, выполнение скрипта hello.py с помощью версии 3.10:

Подобным образом можно вызывать и другие версии Python.

MacOS

На MacOS можно установить разные версии, например, загрузив с официального сайта пакет установщика для определенной версии.

Для обращения к определенной версии Python на MacOS указываем явным образом подверсию в формате python3.[номер_подверсии]. Например, у меня установлена версия
Python 3.10. Проверим ее версию:

Аналогично обращении к версии python3.9 (при условии если она установлена)

К примеру выполнение скрипта hello.py с помощью версии python 3.10:

Linux

На Linux также можно установить одновременно несколько версий Python. Например, установка версий 3.10 и 3.11:

sudo apt-get install python3.10
sudo apt-get install python3.11

Одна из версий является версий по умолчанию. И для обращения к ней достаточно прописать python3, например, проверим версию по умолчанию:

Для обращения к другим версиям надо указывать подверсию:

python3.10 --version
python3.11 --version

Например, выполнение скрипта hello с помощью версии Python 3.10:

Но может сложиться ситуация, когда нам надо изменить версию по умолчанию. В этом случае применяется команда update-alternatives для связывания
определенной версии Python с командой python3. Например, мы хотим установить в качестве версии по умолчанию Python 3.11. В этом случае последовательно выполним следующие команды:

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

Числа справа указывают на приоритет/состояние. Так, для версии 3.11 указан больший приоритет, поэтому при обращении к python3 будет использоваться именно версия 3.11 (в моем случае это Python 3.11.0rc1)

Управление версиями Python в linux

С помощью команды

sudo update-alternatives --config python3

можно изменить версию по умолчанию

Установка версии Python по умолчанию в linux

Environment Variables option to change the Windows 10 or 7 Python version

Python is a well-known programming language when it comes to solving Data Science related problems. It helps in easing down the work of Data Science with the help of its fast execution of codes because of its built Object-Oriented Programming but, there is a problem with this language as well.

Many Pythonists find it difficult to access the correct Python version because of too many Python versions present in their computer system. Due to this, they face problems in downloading the necessary packages in the correct Python version they want.

This leads to many problems in code executions as well as creates confusion for the computer to throw which version at what time.

Now, the question arises of how to resolve this issue and how to add the desired Python version say 3 as the default version on Windows 7/10/11.

The answer to this question is simple and given below. Just make sure that you have 2 or more 2 Python versions downloaded in the system to follow these steps of fixing the issue.

Steps to Change the Default Python Version on Windows 10/11 to Python 3

  • Open your command prompt and check the current Python version the system is using. This will help you get to know which version you are using right now and with which version you want to replace the same.
  • python --version
Check Default Python Version on Windows 10 using command prompt

  • After checking the Python version find the path of your Python versions that will be present most probably in C Drive under the Program Files folder.
  • Open the Program Files folder and locate your Python versions. After locating the same click on the versions and copy the path of the scripts folder of all the Python versions installed.
Find Installed Python folder

Select Pyhton 3 Scripts folder

  • Also, copy the path of the Program Files being present in C Drive.
  • Once the paths are copied the next step is to locate your Environment Variables for the computer. This can be done by right-clicking on the “This PC” option of your computer and clicking on the Properties option. After clicking on the same click on Advanced System Settings under the Properties option.
  • Once done, a pop will come on the screen displaying various options out of which you need to click on the Environment Variables option. The Environment Variables will open up for you and you can see all the system variables present there.
Environment Variables option to change the Windows 10 or 7 Python version

  • The Environment Variablsegregatedgintendednto two different parts that are User Variables and System Variables. Just locate the Path option under the System Variables and click on the same.
  • After clicking on the Path option make sure to put the Scripts and Program Files path of different Python versions that you currently want to use and work in, and where you want to store all your necessary packages should be put first followed by others. Simply, click on the Browse button and select the path of the Script folder and the Python3 itself.
  • Note: Remove any other Python Version available in the System variables, for example, Python2. Select its path and click on the Delete button.
  • Press the OK button to save the changes in the Windowgovernmentalentaltal Variables.
Add Python 3 directory path in Windows 10 or 7

  • Once this is done, restart your Command prompt and again type python --version. Now you will find the desired version there on the system and ready to be usable by the coder.

Conclusion

This is how a user can get his/her Python version when there are multiple versions on the computer. Try this out and start coding with your desired version.

Follow:

The only one thing I know about my self is the «Sharing Is Caring» and you can see here I am doing that…….

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Быстрый ответ

Устанавливайте каждую версию Python с официального сайта, при этом избегайте добавления их в PATH, чтобы не создавать конфликтов. Используйте запускатор py для выбора необходимой версии:

Добавьте шебанг в ваши Python-файлы, который указывает на желаемую версию:

Создавайте виртуальные окружения для каждого проекта с целью контроля версий Python:

Для переключения между версиями используйте инструмент pyenv-win, либо вручную обновите переменную PATH в командной строке.

Кинга Идем в IT: пошаговый план для смены профессии

Дорога к успеху через PATH

Рассматривайте переменную окружения PATH как компас в мире множественных версий Python. Избегайте глобальных изменений, устанавливая PATH локально в каждом окне консоли для соответствующей версии:

Создавайте batch-файлы для автоматизации настройки окружения –- они будут служить вашими настольными помощниками. Пример такого файла (setpython38.bat):

Прибегаем к инкапсуляции: Виртуальная среда

Используйте Virtualenv для контроля зависимостей вашего проекта. Он создает изолированные среды, которые вы можете включать и выключать по своему усмотрению:

После активации вы автоматически переключаетесь на необходимую версию Python:

Либо вернитесь к глобальной версии при помощи команды deactivate.

Получите индивидуальный опыт с Python

Настройте переменную PATHEXT, чтобы запускать Python-скрипты без указания расширения .exe:

Запускатор ‘py’ дает возможность выполнить скрипт с версией Python, указанной в строке шебанга:

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

Визуализация

Воспринимайте использование разных версий Python подобно мастерской с инструментами в операционной системе Windows:

Каждый «инструмент» имеет свое назначение:

Переключение между ними простое и незаметное.

Запускатор ‘py’ – надежный помощник

Запускатор ‘py’ в Windows, описанный в PEP 397, поможет вам управлять версиями Python. Вы можете выбрать нужную версию при помощи опции командной строки:

PEP 397 позволит вам изучить управление версиями Python в Windows.

Конфигурации проекта согласно спецификациям

Используйте .bat или .cmd файлы для настройки окружения каждого проекта, что позволит избегать глобальной настройки:

Двойной клик на batch-файл автоматически запустит ваш скрипт в необходимом окружении.

Полезные материалы

  1. Использование Python на Windows — Документация Python – руководство по установке и настройке.
  2. Управление Python с помощью Conda — альтернативный метод для управления Python-окружениями.
  3. Релизы Python для Windows — прямая ссылка на загрузку версий Python.
  4. Pyenv для Windows на GitHub — смените версии Python как ветер.
  5. Строитель виртуальных сред Python — ваш собственный помощник в управлении проектами.
  6. Документация Tox — инструмент для тестирования Python в различных окружениях.
  7. Добавление путей в Windows – Stack Overflow — искусство конфигурации PYTHONPATH превращает обычного пользователя в специалиста.

Python is a versatile programming language used for various purposes such as data analysis, machine learning, web development, and much more. It can be installed and run on different platforms including Windows, Linux, and macOS.

One common requirement for Python developers is changing the default Python interpreter in the terminal.

This change can be necessary in cases such as the need to work with different Python versions for different projects. In this tutorial, we will guide you through the steps of changing the default Python in your terminal.

Step 1: Check Your Current Python Version

Before proceeding with the changes, it’s important to check your system’s current Python version. This can be done by executing the following command in the terminal:

This command will display the currently installed Python version.

Step 2: Install The Required Python Version

If the Python version that you want to set as default is not already installed on your system, you will need to install it. Please visit the official Python downloads page for installation files and instructions.

Step 3: Change The Default Python Version

Once the desired Python version is installed, you can change the default Python version. In Unix-based systems like Linux and macOS, the command for this would be:

alias python=/usr/bin/python3.8

Replace ‘3.8’ with your Python version. Please note that the exact path to the Python binary could vary based on your operating system and Python distribution.

In Windows, changing the PATH system variable would be necessary which is described in the following step:

Step 4: Update The System PATH (For Windows Users)

In Windows, we need to add the path of the desired Python version to the beginning of the system PATH variable. This can be done through the environment variables in the system settings. More details about this process are available in this Microsoft support documentation.

Conclusion

After successfully following these steps, your terminal should now point to the desired Python interpreter by default.

Remember that these settings are session-specific in Unix-based systems, and the terminal will revert back to the original settings at the end of the session.

To keep the changes across sessions, you may need to update your shell configuration files.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Зачем нужна архивация файлов в windows 7 она что такое
  • Размытое изображение на мониторе windows 10 при загрузке
  • Как установить свою иконку на папку windows 10
  • Как сделать коллаж на windows 10
  • Символьная ссылка на каталог windows