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,
Brock
asked Jul 6, 2010 at 18:42
1
You can use explicit paths:
c:python26python setup.py install
c:python25python setup.py install
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.
Examples:
py -3 setup.py # run latest Python 3
py -2 setup.py # run latest Python 2
py -3.3
py -2.7-32 # use 32-bit version
py # run default version
The default version can be specified in the environment variable PY_PYTHON
, e.g. PY_PYTHON=3
(latest Python 3).
answered Jul 6, 2010 at 20:06
Mark TolonenMark Tolonen
160k24 gold badges168 silver badges242 bronze badges
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.
answered Jul 6, 2010 at 18:46
Alex BliskovskyAlex Bliskovsky
5,6937 gold badges30 silver badges41 bronze badges
1
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:
> python --version
> set PATH=<path-to-desired-python-version>;%PATH%
> python --version
For me it was:
> python --version
Python 3.4.2
> set PATH=C:toolspython2;%PATH%
> python --version
Python 2.7.9
> npm install...
(success)
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..
answered Jan 6, 2015 at 14:38
SethSeth
6,3495 gold badges46 silver badges57 bronze badges
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
All three outlined in this video https://www.youtube.com/watch?v=ynDlb0n27cw
answered May 21, 2017 at 16:53
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)
import sys
from _winreg import *
# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix
regpath = "SOFTWARE\Python\Pythoncore\%s\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\Lib\;%s\DLLs\" % (
installpath, installpath, installpath
)
def RegisterPy():
try:
reg = OpenKey(HKEY_LOCAL_MACHINE, regpath)
except EnvironmentError:
try:
reg = CreateKey(HKEY_LOCAL_MACHINE, regpath)
except Exception, e:
print "*** Unable to register: %s" % e
return
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
print "--- Python %s at %s is now registered!" % (version, installpath)
if __name__ == "__main__":
RegisterPy()
answered Apr 9, 2012 at 2:20
Download Python v2.6.
answered Jul 6, 2010 at 18:43
mcandremcandre
22k19 gold badges87 silver badges145 bronze badges
Последнее обновление: 16.12.2022
На одной рабочей машине одновременно может быть установлено несколько версий Python. Это бывает полезно, когда идет работа с некоторыми внешними библиотеками, которые поддерживают разные версии python, либо в силу каких-то
других причин нам надо использовать несколько разных версий. Например, на момент написания статьи последней и актуальной является версия Python 3.11.
Но, допустим, необходимо также установить версию 3.10, как в этом случае управлять отдельными версиями Python?
Windows
На странице загрузок https://www.python.org/downloads/ мы можем найти ссылку на нужную версию:
И также загрузить ее и установить:
Чтобы при использовании интерпретатора Python не прописывать к нему весь путь, добавим при установке его в переменные среды. Но здесь надо учитывать, что в переменных среды
может содержаться несколько путей к разным интерпретаторам Python:
Та версия 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)
С помощью команды
sudo update-alternatives --config python3
можно изменить версию по умолчанию
Python 3.3 introduces Python Launcher for Windows that is installed into c:Windows
as py.exe
and pyw.exe
by the installer. The installer also creates associations with .py
and .pyw
. Then add #!python3
or #!python2
as the first lline. No need to add anything to the PATH
environment variable.
Update: Just install Python 3.3 from the official python.org/download. It will add also the launcher. Then add the first line to your script that has the .py
extension. Then you can launch the script by simply typing the scriptname.py
on the cmd line, od more explicitly by py scriptname.py
, and also by double clicking on the scipt icon.
The py.exe
looks for C:PythonXXpython.exe
where XX
is related to the installed versions of Python at the computer. Say, you have Python 2.7.6 installed into C:Python27
, and Python 3.3.3 installed into C:Python33
. The first line in the script will be used by the Python launcher to choose one of the installed versions. The default (i.e. without telling the version explicitly) is to use the highest version of Python 2 that is available on the computer.
Python 3.3 introduces Python Launcher for Windows that is installed into c:Windows
as py.exe
and pyw.exe
by the installer. The installer also creates associations with .py
and .pyw
. Then add #!python3
or #!python2
as the first lline. No need to add anything to the PATH
environment variable.
Update: Just install Python 3.3 from the official python.org/download. It will add also the launcher. Then add the first line to your script that has the .py
extension. Then you can launch the script by simply typing the scriptname.py
on the cmd line, od more explicitly by py scriptname.py
, and also by double clicking on the scipt icon.
The py.exe
looks for C:PythonXXpython.exe
where XX
is related to the installed versions of Python at the computer. Say, you have Python 2.7.6 installed into C:Python27
, and Python 3.3.3 installed into C:Python33
. The first line in the script will be used by the Python launcher to choose one of the installed versions. The default (i.e. without telling the version explicitly) is to use the highest version of Python 2 that is available on the computer.
Я установил Python 3.6.5 64-bit и Python 3.6.5 32-bit . Когда я запускаю cmd используется 32-bit . Как можно изменить версию из 32-бит в 64 и обратно?
OC — Windows 7
Возможно это элементано , но новичок )
-
Вопрос заданболее трёх лет назад
-
3335 просмотров
Прописать её в переменной окружения PATH раньше 32-битной. Или просто набирать полный путь до интерпретатора.
Пригласить эксперта
в PATH порядок смени
а лучше удали 32
-
Показать ещё
Загружается…
06 февр. 2023, в 22:33
200000 руб./за проект
06 февр. 2023, в 22:26
2500 руб./за проект
06 февр. 2023, в 22:01
1000 руб./за проект
Минуточку внимания
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.
I hope this solves your problem.
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.
I hope this solves your problem.
Многие сталкиваются с проблемой запуска 2 и 3 версии питона в виндовс. Большая часть софта написана на 2 версии Python, но встречаются хорошие проги на 3.
Допустим у нас установлены версии Python 2.7 и 3.6. Первое что нужно сделать, это добавить C:Python36;C:Python36Scripts;C:Python27;C:Python27Scripts к переменной среды PATH.
Для «тех кто в танке» — это находится здесь ( Windows7 ): Пуск — Панель управления — Система — Дополнительные параметры системы — Переменные среды — Системные переменные. Ищем Path жмём изменить и добавляем вышеописанные строки.
Прекрасно, теперь перейдите в C:Python36, чтобы переименовать python.exe в python3.exe, а также в C:Python27, переименовать python.exe в python2.exe.
Запускаем окно командной строки cmd. Чтобы автоматически распознавалась версия Python всего лишь нужно будет вызвать скрипт командами:
python2 script.py или python3 script.py
Для примера я переписал прогу viSQL со второй версии питона на 3.
Проверяем работоспособность. Для этого перемещаемся в нужный каталог и вводим команду запуска:
Ларчик просто открывался )
-
#2
Вышеописанный способ не идеальный. Например, если тулза попросит поставить зависимость, то командой pip install «имя пакета» у вас ничего не выйдет. Дело в том что в самом pip.exe зашит путь по умолчанию.
Соответственно другой выход есть. Нужно запустить команду pip install «имя пакета» предварительно зайдя в каталог, где находится pip.exe
Но есть и хорошая новость для ленивых, и не любящих лишнее клацание по клаве.
Есть другой вариант, в котором ничего с патчами мутить не нужно.
Есть программа WinPython
При установке создаётся папка, в которой питон и ещё куча других инструментов запускаются прямо из папки, то есть портабл-версия.
Вот так выглядит содержимое папки
На этом всё
-
#3
На самом деле, все еще проще. py -2 или py -3 , для запуска той или иной версии интерпретера.
momentomori
-
#4
помидорами не кидайтесь т.к. мои знания даже не 0 а больше в минус уходят, могу только косячить) Но не буду оправдываться больше, ближе к делу. Устанавливаю питон, то что было в «системные переменной» удалил(почти случайно), стал искать что там было в инете, самое близкое к тосу что помню было C:Windowssystem32;C:Windows;C:Python27Scripts (C:Python27Scripts-это уже сам добавил). Видео смотрел, все вроде так, но почему то все равно пишет так(скрин). Что может быть не так? я уже раз 30 по разному пробовал и версии менял и значения «системные переменной», одна беда. Я в тупике.
питон тут
-
#5
Устанавливаю питон, то что было в «системные переменной» удалил(почти случайно), стал искать что там было в инете, самое близкое к тосу что помню было C:Windowssystem32;C:Windows;C:Python27Scripts (C:Python27Scripts-это уже сам добавил).
В переменных средах должно быть C:Python27;C:Python27Scripts; то есть 2 пути и к папке с питоном и к скриптам
momentomori
-
#6
В переменных средах должно быть C:Python27;C:Python27Scripts; то есть 2 пути и к папке с питоном и к скриптам
Спасибо. А перед этим должна быть какая стандартная строка? Это я так понимаю ей в продолжение, но я попробовал так на всякий, ситуация не изменилась. Скрин приложу как у меня. Но варианты разные конечно пробовал(не факт что правильные) Хотел восстановление сделать, но уже столько раз менял что вчерашнего дня нет уже. В инете тоже везде по разному пишут
-
#7
Спасибо. А перед этим должна быть какая стандартная строка? Это я так понимаю ей в продолжение, но я попробовал так на всякий, ситуация не изменилась. Скрин приложу как у меня. Но варианты разные конечно пробовал(не факт что правильные) Хотел восстановление сделать, но уже столько раз менял что вчерашнего дня нет уже. В инете тоже везде по разному пишут
Когда что-то меняешь и не очень в этом разбираешься, то лучше всегда копировать в текстовый файл. Остальные патчи конечно не нужно было стирать, нужно вернуть от Windows патч.
C:Windowssystem32;C:Windows;
Раз сразу не получилось, удаляйте питон, при переустановке сразу галочкой можно пометить установку патчей.
Кстати восстановление системы windows можно сделать — откатить на тот день, когда ещё ничего не делали.
momentomori
-
#8
Когда что-то меняешь и не очень в этом разбираешься, то лучше всегда копировать в текстовый файл. Остальные патчи конечно не нужно было стирать, нужно вернуть от Windows патч.
C:Windowssystem32;C:Windows;Раз сразу не получилось, удаляйте питон, при переустановке сразу галочкой можно пометить установку патчей.
Кстати восстановление системы windows можно сделать — откатить на тот день, когда ещё ничего не делали.
всё сделал, спасибо) Щас дальше буду колдовать
Introduction
Every fresh Python release comes with bug fixes and new features. Python 3.9, the latest point release at the time of writing, comes with features such as improved time zone support, dictionary updates, and more flexible decorators.
This tutorial shows you how to upgrade Python to version 3.9 on all the major operating systems — Windows, macOS, and Linux.
Prerequisites
- Administrative rights on the operating system you are using.
- Knowledge of which Python version is currently on your system. If you need help finding out the version of your Python installation, check out How to Check Python Version.
Note: If you are upgrading from a Python 2 release and do not have Python 3 installed, read our comprehensive guides on how to install it on:
- Windows 10
- Ubuntu 20.04
- CentOS 8
Upgrading Python on Windows OS
To upgrade Python on Windows, download the installer or search for the app in the Microsoft Store.
Upgrade to Python 3 with the Installer
1. In your browser, visit the Python Releases for Windows section on the official Python website.
2. Click the Download Python button to download the installation file on your computer.
3. Next, run the Python installer. If you are upgrading from another point release of Python 3 (for example, 3.8.10), the installer suggests to install Python 3.9. Select Install Now to install Python with recommended options, or select Customize Installation to pick the install location and features.
If you already have an older version of the same Python release (for example, 3.9.1), the installer offers to upgrade your Python installation. Proceed by selecting Upgrade Now.
4. When the installation finishes, check whether the new version of Python has been installed successfully. Open Windows PowerShell and type:
python3 --version
The output should show the latest version of Python, as in the image below.
Install Python 3.9 from the Microsoft Store
If you want to use Python 3.9 to learn the basics or test some simple concepts, find and install the Python 3.9 app from the Microsoft Store.
1. Go to Microsoft Store and type Python in the search field.
2. Select Python 3.9 from the search results that appear.
3. Click the Get button to start the installation.
Start the interactive Python 3.9 experience by finding the app in the Start Menu.
Upgrading Python on macOS
On macOS, Python can be installed, upgraded, and maintained using the command line interface or the GUI.
Upgrade Python using Homebrew
Install Python in the macOS terminal using the Homebrew package manager. If you do not have Homebrew, install it by typing the following script in the terminal:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
Then, proceed with the steps:
1. Update Homebrew by running:
brew update
2. If you are upgrading from Python 2, install Python 3 with the command:
brew install python3
If you already have a version of Python 3 installed, upgrade the package with the brew upgrade
command:
brew upgrade python3
Upgrade Python with the Installer
1. In your browser, navigate to the Python Releases for macOS page, on Python’s official website.
2. Click the link to download the latest Python 3 release on your computer.
3. Run the installer. Go through the installation steps by clicking Continue, agreeing to the License, and confirming the installation location and type.
4. Once the installation is complete, select Close.
5. Finally, confirm that the new Python version has been successfully installed by typing the following in terminal:
python3 --version
The output should display the latest version of Python.
Upgrading Python in Linux
This article uses Ubuntu and its APT package manager to upgrade Python. If you are using a different Linux distribution, replace the apt Linux command with the appropriate command featured for your package manager.
Warning: Many Linux systems have Python 2 installed as the system version. Removing Python 2 could cause a system error. If you are planning to install Python 3 on Linux, install it alongside Python 2 and invoke it with the python3
command.
1. Start by updating the repositories:
sudo apt update
2. Next, install Python 3.9 by running:
sudo apt install python3.9
When prompted, type Y to start the installation.
3. Once Python installs, invoke the 3.9 version by running:
python3.9
4. However, checking the installation with the python3 --version
command still returns the old version. To fix this, you need to create a list of update alternatives. First, add the old version to the list with the command:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.[old-version] 1
5. Now add the new version:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 2
6. Next, type the following command to configure the priority status of the versions:
sudo update-alternatives --config python3
The output displays the available choices and their assigned number (in the example below, the numbers are 0, 1, 2). Type the number of the the version you wish to use and press Enter.
7. If you are not planning to use the old version of Python, remove the symlink that contained the previous Python 3 version with:
sudo rm /usr/bin/python3
8. Then, replace the symlink with the new version:
sudo ln -s python3.9 /usr/bin/python3
9. Now, check the default version:
python3 --version
The output should confirm the successful installation and setup of the latest available version.
Why Should You Upgrade Python?
Since Python 3 was not a backward-compatible release, for a long time Python 2 remained the version of choice for those who wanted a stable development environment. Some services like Google App Engine did not support Python 3 for a long time.
However, given that the official support for the final Python 2.7 release has ended, upgrading to Python 3 is now strongly recommended. Python 3 is faster, and its syntax is more user-friendly.
If you already work with Python 3, upgrading to the latest point release gives you all the security updates and bug fixes.
Conclusion
After reading this tutorial, you should know how to upgrade your Python 3 version on Windows, macOS, and Linux. If you want to learn more about Python, read our article on Python data types.