Как поменять версию 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

I installed Python 2.6 and Python 3.1 on Windows 7 and set environment variable: path = d:\python2.6.

When I run python in cmd, it displays the python version 2.6, which is what I want!
But, when I wrote a script in a bat file and ran it, the displayed python version was 3.1.

import sys
print (sys.version)

What’s going on here?

Mark Tolonen's user avatar

Mark Tolonen

167k26 gold badges169 silver badges251 bronze badges

asked Feb 23, 2011 at 6:47

rooney's user avatar

2

This is if you have both the versions installed.

Go to This PCRight-clickClick on PropertiesAdvanced System Settings.

You will see the System Properties. From here navigate to the Advanced Tab -> Click on Environment Variables.

You will see a top half for the user variables and the bottom half for System variables.

Check the System Variables and double-click on the Path (to edit the Path).

Check for the path of Python(which you wish to run i.e. Python 2.x or 3.x) and move it to the top of the Path list.

Restart the Command Prompt, and now when you check the version of Python, it should correctly display the required version.

Neuron's user avatar

Neuron

5,1875 gold badges38 silver badges60 bronze badges

answered Oct 21, 2018 at 7:30

Aditya Deshpande's user avatar

Aditya DeshpandeAditya Deshpande

1,7561 gold badge10 silver badges12 bronze badges

6

The Python installer installs Python Launcher for Windows. This program (py.exe) is associated with the Python file extensions and looks for a «shebang» comment to specify the python version to run. This allows many versions of Python to co-exist and allows Python scripts to explicitly specify which version to use, if desired. If it is not specified, the default is to use the latest Python version for the current architecture (x86 or x64). This default can be customized through a py.ini file or PY_PYTHON environment variable. See the docs for more details.

Newer versions of Python update the launcher. The latest version has a py -0 option to list the installed Pythons and indicate the current default.

Here’s how to check if the launcher is registered correctly from the console:

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Windows\py.exe" "%1" %*

Above, .py files are associated with the Python.File type. The command line for Python.File is the Python Launcher, which is installed in the Windows directory since it is always in the PATH.

For the association to work, run scripts from the command line with script.py, not «python script.py», otherwise python will be run instead of py. If fact it’s best to remove Python directories from the PATH, so «python» won’t run anything and enforce using py.

py.exe can also be run with switches to force a Python version:

py -3 script.py       # select latest Python 3.X version to be used.
py -3.6 script.py     # select version 3.6 specifically.
py -3.9-32 script.py  # select version 3.9 32-bit specifically.
py -0                 # list installed Python versions (latest PyLauncher).

Additionally, add .py;.pyw;.pyc;.pyo to the PATHEXT environment variable and then the command line can just be script with no extension.

answered Feb 23, 2011 at 8:31

Mark Tolonen's user avatar

Mark TolonenMark Tolonen

167k26 gold badges169 silver badges251 bronze badges

4

Running ‘py’ command will tell you what version you have running. If you currently running 3.x and you need to switch to 2.x, you will need to use switch ‘-2’

py -2

If you need to switch from python 2.x to python 3.x you will have to use ‘-3’ switch

py -3

If you would like to have Python 3.x as a default version, then you will need to create environment variable ‘PY_PYTHON’ and set it’s value to 3.

answered Jan 14, 2017 at 13:19

Vlad Bezden's user avatar

Vlad BezdenVlad Bezden

84.3k25 gold badges248 silver badges181 bronze badges

3

If you know about Environment variables and the system variable called path, consider that any version of any binary which comes sooner, will be used as default.

Look at the image below, I have 3 different python versions but python 3.8 will be used as default since it came sooner than the other two. (In case of mentioned image, sooner means higher!)

enter image description here

answered Jan 23, 2020 at 7:49

AmiNadimi's user avatar

AmiNadimiAmiNadimi

5,1893 gold badges39 silver badges55 bronze badges

0

If you are a Windows user and you have a version of Python 3.3 or greater, you should have the Python Launcher for Windows installed on your machine, which is the recommended way to use for launching all python scripts (regardless of python version the script requires).

As a user

  • Always type py instead of python when running a script from the command line.

  • Setup your «Open with…» explorer default program association with C:\Windows\py.exe

  • Set the command line file extension association to use the Python Launcher for Windows (this will make typing py optional). In an Admin cmd terminal, run:

    ftype Python.File="C:\Windows\py.exe" "%L" %*

    ftype Python.NoConFile="C:\Windows\pyw.exe" "%L" %*

  • Set your preferred default version by setting the PY_PYTHON environment variable (e.g. PY_PYTHON=3.11). You can see what version of python is your default by typing py. You can also set PY_PYTHON3 or PY_PYTHON2 to specify default python 3 and python 2 versions (if you have multiple).

  • If you need to run a specific version of python, you can use py -M.m (where M is the major version and m is the minor version). For example, py -3 will run any installed version of python 3.

  • List the installed versions of python with py -0.

As a script writer

  • Include a shebang line at the top of your script that indicates the major version number of python required. If the script is not compatible with any other minor version, include the minor version number as well. For example:

    #!/usr/bin/env python3

    Note: (see this question) If python3 does not work for you, ensure that you’ve installed python from the Windows Store (e.g. via winget install --id 9NRWMJP3717K, as the winget package Python.Python.3.11 does not appear to include a python3.exe).

  • You can use the shebang line to indicate a virtual environment as well (see PEP 486 below).


See also

  • PEP 397 — Python launcher for Windows
  • PEP 486 — Make the Python Launcher aware of virtual environments
  • Python Launcher for Windows — User Guide

answered Aug 2, 2019 at 23:02

Casey Kuball's user avatar

Casey KuballCasey Kuball

7,7175 gold badges39 silver badges70 bronze badges

1

See here for original post

;
; This is an example of how a Python Launcher .ini file is structured.
; If you want to use it, copy it to py.ini and make your changes there,
; after removing this header comment.
; This file will be removed on launcher uninstallation and overwritten
; when the launcher is installed or upgraded, so don't edit this file
; as your changes will be lost.
;
[defaults]
; Uncomment out the following line to have Python 3 be the default.
;python=3

[commands]
; Put in any customised commands you want here, in the format
; that's shown in the example line. You only need quotes around the
; executable if the path has spaces in it.
;
; You can then use e.g. #!myprog as your shebang line in scripts, and
; the launcher would invoke e.g.
;
; "c:\Program Files\MyCustom.exe" -a -b -c myscript.py
;
;myprog="c:\Program Files\MyCustom.exe" -a -b -c

Thus, on my system I made a py.ini file under c:\windows\ where py.exe exists, with the following contents:

[defaults]
python=3

Now when you Double-click on a .py file, it will be run by the new default version. Now I’m only using the Shebang #! python2 on my old scripts.

answered May 11, 2013 at 21:48

Ehsan Iran-Nejad's user avatar

Ehsan Iran-NejadEhsan Iran-Nejad

1,6971 gold badge15 silver badges20 bronze badges

0

  1. Edit registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\python.exe\default
  2. Set default program to open .py files to python.exe

Druid's user avatar

Druid

6,4334 gold badges41 silver badges56 bronze badges

answered Aug 2, 2012 at 3:14

cuble's user avatar

cublecuble

3062 silver badges7 bronze badges

This work for me.

If you want to use the python 3.6 you must move the python3.6 on the top of the list.

The same applies to the python2.7
If you want to have the 2.7 as default then make sure you move the python2.7 on the very top on the list.

step 1

enter image description here

step 2

enter image description here

step 3

enter image description here

then close any cmd command prompt and opened again, it should work as expected.

python —version

>>> Python 3.6

answered Dec 22, 2018 at 1:07

1

With Python versions 2.7, 3.7, 3.9, and 3.11 installed on my Windows 11 OS, I encountered issues with the previously suggested solutions. However, I found a straightforward method that worked for me.

First, let’s understand how to set the default Python version using the py command. Running py --help provides hints, including a reference to the py.ini file located in %LOCALAPPDATA%\py.ini. This file allows us to specify the default Python version.

To set a specific default Python version:

  1. Open a text editor or create a file in %LOCALAPPDATA%\py.ini.

  2. Add the following content to the py.ini file:

[defaults]
python=3.7
  1. Save the file.

Now, when you run py --version in the console, it should display the specified default Python version.

Please note the following additional points to consider:

  • Purpose of setting the default Python version: Setting a specific default Python version can be helpful for ensuring compatibility with certain dependencies or maintaining consistency across projects.

  • Location of %LOCALAPPDATA%: The %LOCALAPPDATA% environment variable typically refers to C:\Users\<username>\AppData\Local. If the py.ini file does not exist in that location, you can create it manually.

answered Aug 4, 2022 at 11:30

flydev's user avatar

flydevflydev

4,4372 gold badges32 silver badges36 bronze badges

2

This worked for me:

Go to

Control Panel\System and Security\System

select

Advanced system settings from the left panel
from Advanced tab click on Environment Variables

In the System variables section search for (create if doesn’t exist)

PYTHONPATH

and set

C:\Python27\;C:\Python27\Scripts;

or your desired version

You need to restart CMD.

In case it still doesn’t work you might want to leave in the PATH variable only your desired version.

answered Nov 14, 2017 at 0:24

George B's user avatar

George BGeorge B

4141 gold badge7 silver badges17 bronze badges

Now that Python 3.3 is released it is easiest to use the py.exe utility described here:
http://www.python.org/dev/peps/pep-0397/

It allows you to specify a Python version in your script file using a UNIX style directive. There are also command line and environment variable options for controlling which version of Python is run.

The easiest way to get this utility is to install Python 3.3 or later.

answered Jan 3, 2013 at 5:57

Gerald's user avatar

GeraldGerald

6095 silver badges13 bronze badges

If you are on Windows, use the ASSOC command to change the default python version for python programs.

assoc .py=<Python 3.1 directory>

answered Jul 23, 2021 at 8:08

DerpyCoder's user avatar

DerpyCoderDerpyCoder

1271 silver badge6 bronze badges

Nothing above worked, this is what worked for me:

ftype Python.File=C:\Path\to\python.exe "%1" %*

This command should be run in Command prompt launched as administrator

Warning: even if the path in this command is set to python35, if you have python36 installed it’s going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36 to xxPython36, run the command and then remove the change to the Python 36 folder.


Edit: This is what I ended up doing: I use Python Launcher.
https://stackoverflow.com/a/68139696/3154274

answered Nov 30, 2016 at 6:30

MagTun's user avatar

MagTunMagTun

5,6695 gold badges63 silver badges104 bronze badges

2

Check which one the system is currently using:

python --version

Add the main folder location (e.g. C/ProgramFiles) and Scripts location (C/ProgramFiles/Scripts) to Environment Variables of the system. Add both 3.x version and 2.x version

Path location is ranked inside environment variable. If you want to use Python 2.x simply put path of python 2.x first, if you want for Python 3.x simply put 3.x first

This uses python 2

answered Apr 6, 2018 at 9:06

pranavhd's user avatar

I had same problem and solve it by executing the installation file again. when you do that python automatically knows you have installed it before so it recommends you 3 options! select modify and select all packages you want to modify then in the next page you can check if new version of python is added to your environment variables or not. check it and then execute modification. I did and it solved.

answered Oct 16, 2022 at 8:41

Amir Sadeqi's user avatar

3

Since my problem was slightly different and none of the above worked for me, I’ll add what worked for me. I had installed the new python launcher for python 3.10 today, installed the version through it, but the command window did not recognise the version. Instead, it listed older python3 versions I had on my computer.

Finally, in the windows programs list, I saw that I had two versions of the python launcher. I uninstalled the old one, and now python 3.10 shows up correctly when running py -0 and is the chosen version when running py.

Apologies if this is a noob answer, I am new to all this.

answered Aug 8, 2022 at 7:17

Draenth's user avatar

Set PY_PYTHON environment variable as 2.6 (or any version you want). Restart the terminal or cmd and type py -0p. The 2.6 should have a * next to it indicating that’s the default python version now.

answered May 18 at 1:06

vinodhraj's user avatar

vinodhrajvinodhraj

1771 silver badge7 bronze badges

Use SET command in Windows CMD to temporarily set the default python for the current session.

SET PATH=C:\Program Files\Python 3.5

answered Oct 22, 2016 at 14:31

ron4ex's user avatar

ron4exron4ex

1,08310 silver badges21 bronze badges

Try modifying the path in the windows registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment).

Caveat: Don’t break the registry :)

answered Feb 23, 2011 at 6:54

phooji's user avatar

phoojiphooji

10.1k2 gold badges38 silver badges45 bronze badges

2

Im trying to switch between python versions 3.6.6 and 3.7.0 in windows. I tried py -3.6.6 and doesn’t work. Looked for options in py -h, found none. I saw a couple of answers for switching between python versions 2.x and 3.x by adding #!python3 at the start of the file.

I’m able to switch between these by moving path variables up and down but I want to know if there is a option to switch between versions in cmd like there is brew switch python version in IOS.

Thank you.

asked Sep 2, 2018 at 2:35

Tarun Kolla's user avatar

If You have python of the same version with different subversion e.g. 2.6, 3.7,.. 3.9.
Use the below command to open specific python version’s terminal in command prompt:

py -2.6
py -3.7
.

for installing modules in command prompt:

py -2.6 -m pip install <modules>
py -3.7 -m pip install <modules>

answered Dec 2, 2020 at 6:35

NevetsKuro's user avatar

NevetsKuroNevetsKuro

6447 silver badges15 bronze badges

1

The easiest way is simply type py -2 if you want to use python2, and py -3 if you want to use python3.

Hoppo's user avatar

Hoppo

1,1401 gold badge13 silver badges32 bronze badges

answered Jun 15, 2020 at 21:07

Zhe Huang's user avatar

Change the path in environment variable after downloading python 3.7.0 in windows where you can find in the properties of My Computer in Advanced System Settings

answered Sep 2, 2018 at 3:12

Akash Badam's user avatar

Akash BadamAkash Badam

4762 silver badges9 bronze badges

1

If you need to use multiple versions of Python, or run different sets of packages in the Python environment, you should probably just use Anaconda to create them, for example:

    conda create -n py36 python=3.6 anaconda

then you can just switch between them using

    activate <your-environment-name>

answered Sep 2, 2018 at 3:12

Ho John Lee's user avatar

2

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.

Windows

Изменение Python по умолчанию в Windows является относительно простым, потому что вы можете вручную изменить системные переменные среды

1. Узнайте, установлена ​​ли на вашем компьютере другая версия python или конфликтует ли установленный вручную python с питоном, который поставляется с anaconda / miniconda

2. В любом случае, вам нужно выяснить путь различных версий Python

3. Откройте системные переменные среды и дважды щелкните для редактирования в пути под пользовательскими переменными. Как правило, после того, как вы откроете его, вы увидите несколько различных путей к python, сохраните то, что вам нужно, или удалите все пути python и добавите путь к нужной версии.

4. Помните, что после внесения каких-либо изменений в переменные среды (вручную или автоматически после установки определенных программ) открытая консоль не обновляется, поэтому необходимо перезапустить консоль. Более того, поскольку программа записала данные кеша в / Temp на системном диске, эти данные после обновления сохранят содержимое старой версии, а также создадут конфликт в вашей новой среде сборки, что обеспечит защиту от ошибок. Вы можете перезагрузить компьютер, иУдалить недавно сгенерированные данные кэша в / Temp

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

Macos

Конечно, это не очень сложно на макросах

Для ясности, macos поставляется с функцией Python версии 2.7, поэтому ввод python в Terminal обычно указывает на эту версию. Кроме того, если вы устанавливаете версию Python 3.X самостоятельно, вы сможете использовать свою собственную версию, используя соответствующие команды python3 и pip3 (окончание 3). Итак, если ваша проблема также является конфликтом между обычным питоном и миникондой / анакондой, то вы можете выполнить следующие шаги

1. Откройте Терминал и введите

open ~/.bash_profile

2. В это время откроется редактируемый документ, похожий на переменную среды Windows.В этой переменной среды, которую вы недавно добавили самостоятельно, все, что вам нужно сделать, — это просто удалить ненужный путь к python.И следуйте тому же формату,Введите путь, где вам нужен питон, а затем закройте этот файл

3. Перезагрузите терминал

  • Как поменять версию сборки windows 10
  • Как поменять версию windows 10 с корпоративной на pro
  • Как поменять белый цвет окон в windows 10
  • Как поменять баланс звука в windows 10
  • Как поменять атрибуты файла в windows