- Как обновить Python в Windows в 2021 году?
- Введение
- Узнаем текущую версию
- Скачиваем последнюю версию
- Установка
- Проверка установки
- Заключение
- Windows Command Line Python Change Version
- 6 Answers 6
- How to change python version in command prompt if I have 2 python version installed
- 6 Answers 6
- How Should I Set Default Python Version In Windows?
- 14 Answers 14
- How to run multiple Python versions on Windows
- 18 Answers 18
Как обновить Python в Windows в 2021 году?
Подробно рассмотрим как правильно обновить язык программирования Python.
Введение
Технологии развиваются быстро, а языки программирования — это основной драйвер развития. Нередко выходят корректирующие релизы исправляющие найденные ошибки или версии с расширением функционала. Python в этом плане ничем не отличается от других языков программирования, но процесс его обновления не столь сложен, как может показаться сначала. Если у вас получится обновить один раз, вы уже не забудете как его повторить, потому что это не сложно и очень быстро.
Узнаем текущую версию
Открываем пуск -> выполнить -> вводим команду cmd. В открывшемся окне пишем команду python —version и смотрим какая у нас версия.
Скачиваем последнюю версию
Переходим на официальный сайт www.python.org/downloads/ и скачиваем последнюю версию
Нажимаем кнопочку Download Python и скачиваем дистрибутив
Установка
Так как у меня установлена уже последняя версия Python мне пришлось скачать beta версию для демонстрации процесса обновления. Не пугайтесь из за того, что на картинках другая версия, это не ошибка 🙂
Ставим обязательно галочку перед пунктом Add Python 3.9 to PATH.
Нажимаем Install Now и переходим далее.
Обязательно предоставляем полные права приложению
Дожидаемся окончания процесса установки и в конце нажимаем Close
Проверка установки
В самом начале я описал процесс сверки текущий версии Python. Нам сейчас это необходимо повторить, только предварительно перезапустив окно cmd.exe иначе запуститься python старой версии 🙂
Заключение
В этой статье мы рассмотрели процесс обновления языка программирования Python, прошли от первого до последнего шага и успешно завершили обновление.
На это все. Поздравляю, теперь у вас установлена последняя версия Python.
Если вам интересны статьи о теме Python вы можете познакомиться с ними по этой ссылке.
Если вы ищите способ системно подойти к обучению языка программирования Python, рекомендую записаться на курсы онлайн обучения.
Поделиться записью в социальных сетях
Windows Command Line Python Change Version
New to Python and programming in general. I want to «install» a module from the command line for v 2.6, but it looks like my default Python is 2.5. (python —version returns 2.5.4)
How can I run my python setup.py build/install on 2.6 instead?
Many thanks in advance,
6 Answers 6
It depends on your operating system. If you have python 2.6 installed, you need to change your environment path to point to the 2.6 executable rather than the 2.5 executable. Do a Google search for changing your PATH variable on your operating system.
You can use explicit paths:
Recent versions of Python install PyLauncher. It is installed in the path so no need to add an explicit Python to the path, and it allows easy switching between multiple Python versions.
The default version can be specified in the environment variable PY_PYTHON , e.g. PY_PYTHON=3 (latest Python 3).
If you’re on Windows and you just need to run a different version of Python temporarily or, as was the case for me, a third party program needs to run a different version of Python, then modify your path at the command prompt:
This allowed the third party program to install successfully. The PATH modification only affects programs running in the same command prompt session and only lasts as long as the command prompt session..
They are a couple of ways you can do this 1) python virtual environment 2) pylauncher 3) Changing your windows path variable, tedious to say the least
It sounds like you are on windows. If so, run this with the python you want, to set that python as the windows one. (not my code)
How to change python version in command prompt if I have 2 python version installed
I have installed Anaconda 2 & 3 in my system. Anaconda 2 contains python 2.7 & Anaconda 3 contains python 3.6 .
I need to run my python code using command prompt & I need to use python 3.6 While I’m running python —version , I’m getting python 2.7.14 . How do I change it to python 3.6?
6 Answers 6
As you can see, I have both Python2 and Python3 installed.
I hope you know that the path of the python executable has to be added to the PATH environment variable in Windows. As you can see, the path of Python2 is placed above the path of Python3 in my system.
How does the cmd run commands?
It searches for an executable with the same name in the directory the cmd has been opened in, then goes and searches for the command in the locations provided in the Windows PATH variable, from TOP to BOTTOM. Which means, it gets the path to Python2 before it can get to the path of Python3. Therefore, every time you type python in your cmd, it runs Python2.
Both Python2 and Python3 executables have the same name in Windows so it never runs python3.
What seems like an obvious solution?
You might think, changing the name of python.exe to python3.exe for the Python3 executable will solve your problem. You are partially right, it will work. But you have to use python3 file.py or python3 —version , which I think, is understandable. But, pip will no longer work if you change the name of the original python executable. You will no longer be able to install external packages and modules.
How can this problem be solved?
You can create an alias for the Python3 executable called python3.bat .
.exe and .bat files can be called from the cmd directly without using their extension. We always write python filename.py instead of python.exe filename.py although both are correct. The same can be done with .bat files.
Go back to the first image and notice the python3.bat file below python.exe . That is my way of calling python3 without renaming my original python executable.
python3.bat
Create a new file using notepad or something and paste this %
dp0python %*
I don’t fully understand how this works except that dp0 basically runs python from inside the same directory and %* passes all the arguments to the python executable. Place this file inside your Python3 installation directory and your problem will hopefully be solved.
python3 basically runs your python3.bat file, which in turn runs the python.exe from its folder and passes the arguments to it.
How Should I Set Default Python Version In Windows?
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.
What’s going on here?
14 Answers 14
This is if you have both the versions installed.
Go to This PC -> Right-click -> Click on Properties -> Advanced 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.
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:
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:
Additionally, add .py;.pyw;.pyc;.pyo to the PATHEXT environment variable and then the command line can just be script with no extension.
How to run multiple Python versions on Windows
I had two versions of Python installed on my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another.
How can I specify which I want to use?
I am working on Windows XP SP2.
18 Answers 18
Running a different copy of Python is as easy as starting the correct executable. You mention that you’ve started a python instance, from the command line, by simply typing python .
What this does under Windows, is to trawl the %PATH% environment variable, checking for an executable, either batch file ( .bat ), command file ( .cmd ) or some other executable to run (this is controlled by the PATHEXT environment variable), that matches the name given. When it finds the correct file to run the file is being run.
Now, if you’ve installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like PATH=c:\python\2.5;c:\python\2.6 but Windows will stop examining the path when it finds a match.
What you really need to do is to explicitly call one or both of the applications, such as c:\python\2.5\python.exe or c:\python\2.6\python.exe .
The other alternative is to create a shortcut to the respective python.exe calling one of them python25 and the other python26 ; you can then simply run python25 on your command line.
Adding two more solutions to the problem:
- Use pylauncher (if you have Python 3.3 or newer there’s no need to install it as it comes with Python already) and either add shebang lines to your scripts;
#! c:\[path to Python 2.5]\python.exe — for scripts you want to be run with Python 2.5
#! c:\[path to Python 2.6]\python.exe — for scripts you want to be run with Python 2.6
or instead of running python command run pylauncher command ( py ) specyfing which version of Python you want;
py -2.6 – version 2.6
py -2 – latest installed version 2.x
py -3.4 – version 3.4
py -3 – latest installed version 3.x
- Install virtualenv and create two virtualenvs;
virtualenv -p c:\[path to Python 2.5]\python.exe [path where you want to have virtualenv using Python 2.5 created]\[name of virtualenv]
virtualenv -p c:\[path to Python 2.6]\python.exe [path where you want to have virtualenv using Python 2.6 created]\[name of virtualenv]
virtualenv -p c:\python2.5\python.exe c:\venvs\2.5
virtualenv -p c:\python2.6\python.exe c:\venvs\2.6
then you can activate the first and work with Python 2.5 like this
c:\venvs\2.5\activate
and when you want to switch to Python 2.6 you do
From Python 3.3 on, there is the official Python launcher for Windows (http://www.python.org/dev/peps/pep-0397/). Now, you can use the #!pythonX to determine the wanted version of the interpreter also on Windows. See more details in my another comment or read the PEP 397.
Summary: The py script.py launches the Python version stated in #! or Python 2 if #! is missing. The py -3 script.py launches the Python 3.
As per @alexander you can make a set of symbolic links like below. Put them somewhere which is included in your path so they can be easily invoked
As long as c:\bin or where ever you placed them in is in your path you can now go
For example for 3.6 version type py -3.6 . If you have also 32bit and 64bit versions, you can just type py -3.6-64 or py -3.6-32 .
- PYTHON2_HOME: C:\Python27
- PYTHON3_HOME: C:\Python36
- Path: %PYTHON2_HOME%;%PYTHON2_HOME%\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\Scripts;
- C:\Python27\python.exe → C:\Python27\python2.exe
- C:\Python36\python.exe → C:\Python36\python3.exe
- python2 -m pip install package
- python3 -m pip install package
@山茶树和葡萄树 – Bright Chang Jun 15 ’20 at 15:18
When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.
So you can just install it. Then you call the Python version you want. For example:
for Python 2.5 on windows and
for Python 2.6 on windows, or
on Windows Unix (including Linux and OS X).
When you install on Unix (including Linux and OS X) you will get a generic python command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don’t want to do that, and you probably don’t you can install it like this:
Note the «altinstall» that means it will install it, but it will not replace the python command.
On Windows you don’t get a global python command as far as I know so that’s not an issue.
I strongly recommend the pyenv-win project.
Thanks to kirankotari’s work, now we have a Windows version of pyenv.
Here’s a quick hack:
- Go to the directory of the version of python you want to run
- Right click on python.exe
- Select ‘Create Shortcut‘
- Give that shortcut a name to call by( I use p27, p33 etc.)
- Move that shortcut to your home directory( C:\Users\Your name )
- Open a command prompt and enter name_of_your_shortcut.lnk (I use p27.lnk )
One easy way for this is that you can use
py -3.8 -m pip install virtualenv here -3.8 goes with your [version number]
After installing the virtualenv, you can create the virtual environment of your application using
py -3.8 -m virtualenv [your env name]
then cd to venv, enter activate
This would activate the python version you like. Just change the version number to use a different python version.
cp c:\python27\bin\python.exe as python2.7.exe
cp c:\python34\bin\python.exe as python3.4.exe
they are all in the system path, choose the version you want to run
The easiest way to run multiple versions of python on windows is described below as follows:-
1)Download the latest versions of python from python.org/downloads by selecting the relevant version for your system.
2)Run the installer and select Add python 3.x to the path to set path automatically in python 3 (you just have to click the checkbox). For python 2 open up your python 2 installer, select whatever preferences you want but just remember to set Add python.exe to path to Will be installed on local hard drive, Now just click next and wait for the installer to finish.
3)When both the installations are complete. Right click on my computer—Go to properties—Select advanced system settings—Go to environment variables—Click on new under System variables and add a new system variable with variable name as PY_PYTHON and set this variable value to 3. Now click on OK and you should be done.
4)Now to test this open the command prompt. Once you are in there type python or py, It should open up python3.
5)Now exit out of python3 by typing exit(). Now type py -2 it should open python 2.
If none of this works then restart the computer and if the problem still persists then uninstall everything and repeat the steps.