[updated for 2021]
(Regardless if you are on Mac, Linux, or Windows:)
If you are confused about how to start the latest version of python, on most platforms it is the case that python3
leaves your python2
installation intact (due to the above compatibility reasons); thus you can start python3 with the python3
command.
Historically…
The naming convention is that generally, most scripts will call python2 or python3 explicitly. This happened due to a need for backwards compatibility.
Even though technically python doesn’t even guarantee backwards compatibility between minor versions, Python3 really breaks backwards compatibility. At the time, programs invoking ‘python
‘ were expecting python2 (which was the main version at the time). Extremely old systems may have programs and scripts which expect python
=python2, and changing this would break those programs and scripts.
At the time this answer was written, OP should not have changed this due to maintaining compatibility for old scripts.
Circa year 2021…
Nowadays, many years after the python2->python3 transition, most software explicitly refers to python2 or python3 (at least on Linux). For example, they might call #!/usr/bin/env python2
or #!/usr/bin/env python3
. This has for example (python-is-python3-package) freed up the python command to be settable to a user default, but it really depends on the operating system.
The prescription for how distributions should handle the python
command was written up in 2011 as PEP 394 — The «python» Command on Unix-Like Systems. It was last updated in June 2019.
Basically if you are writing a library, you should specify the version of python (2 or 3, or finer-grained under specific circumstances) you can use. Otherwise as an end user, you should feel free to rename this for your own personal use (though your OS or distribution may not make that easy).
Shell alias:
You could, however, make a custom alias in your shell. The way you do so depends on the shell, but perhaps you could do alias py=python3
, and put it in your shell startup file. This will only work on your local computer (as it should), and is somewhat unnecessary compared to just typing it out (unless you invoke the command constantly).
Confused users should not try to create aliases or virtual environments or similar that make python
execute python3
; this is poor form.This is acceptable nowadays, but PEP 394 suggests encouraging users to use a virtualenv instead.
Different 3.* versions, or 2.* versions:
In the extremely unlikely case that if someone comes to this question with two python3 versions e.g. 3.1 vs 3.2, and you are confused that you have somehow installed two versions of python, this is possibly because you have done manual and/or manual installations. You can use your OS’s standard package/program install/uninstall/management facilities to help track things down, and perhaps (unless you are doing dev work that surprisingly is impacted by the few backwards-incompatible changes between minor versions) delete the old version (or do make uninstall
if you did a manual installation). If you require two versions, then reconfigure your $PATH
variable so the ‘default’ version you want is in front; or if you are using most Linux distros, the command you are looking for is sudo update-alternatives
. Make sure any programs you run which need access to the older versions may be properly invoked by their calling environment or shell (by setting up the var PATH
in that environment).
A bit about $PATH
sidenote: To elaborate a bit on PATH: the usual ways that programs are selected is via the PATH
(echo $PATH
on Linux and Mac) environment variable. You can always run a program with the full path e.g. /usr/bin/🔳 some args
, or cd /usr/bin
then ./🔳 some args
(replace blank with the ‘echo’ program I mentioned above for example), but otherwise typing 🔳 some args
has no meaning without PATH
env variable which declares the directories we implicitly may search-then-execute files from (if /usr/bin
was not in PATH
, then it would say 🔳: command not found
). The first matching command in the first directory is the one which is executed (the which
command on Linux and Mac will tell you which sub-path this is). Usually it is (e.g. on Linux, but similar on Mac) something like /usr/bin/python
which is a symlink to other symlinks to the final version somewhere, e.g.:
% echo $PATH
/usr/sbin:/usr/local/bin:/usr/sbin:usr/local/bin:/usr/bin:/bin
% which python
/usr/bin/python
% which python2
/usr/bin/python2
% ls -l /usr/bin/python
lrwxrwxrwx 1 root root 7 Mar 4 2019 /usr/bin/python -> python2*
% ls -l /usr/bin/python2
lrwxrwxrwx 1 root root 9 Mar 4 2019 /usr/bin/python2 -> python2.7*
% ls -l /usr/bin/python2.7
-rwxr-xr-x 1 root root 3689352 Oct 10 2019 /usr/bin/python2.7*
% which python3
/usr/bin/python3
% ls -l /usr/bin/python3
lrwxrwxrwx 1 root root 9 Mar 26 2019 /usr/bin/python3 -> python3.7*
% ls -l /usr/bin/python3.7
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7*
% ls -l /usr/bin/python*
lrwxrwxrwx 1 root root 7 Mar 4 2019 /usr/bin/python -> python2*
lrwxrwxrwx 1 root root 9 Mar 4 2019 /usr/bin/python2 -> python2.7*
-rwxr-xr-x 1 root root 3689352 Oct 10 2019 /usr/bin/python2.7*
lrwxrwxrwx 1 root root 9 Mar 26 2019 /usr/bin/python3 -> python3.7*
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7*
lrwxrwxrwx 1 root root 33 Apr 2 2019 /usr/bin/python3.7-config -> x86_64-linux-gnu-python3.7-config*
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7m*
lrwxrwxrwx 1 root root 34 Apr 2 2019 /usr/bin/python3.7m-config -> x86_64-linux-gnu-python3.7m-config*
lrwxrwxrwx 1 root root 16 Mar 26 2019 /usr/bin/python3-config -> python3.7-config*
lrwxrwxrwx 1 root root 10 Mar 26 2019 /usr/bin/python3m -> python3.7m*
lrwxrwxrwx 1 root root 17 Mar 26 2019 /usr/bin/python3m-config -> python3.7m-config*
sidenote2: (In the rarer case a python program invokes a sub-program with the subprocess
module, to specify which program to run, one can modify the paths of subprocesses with sys.path
from the sys module or the PYTHONPATH
environment variable set on the parent, or specifying the full path… but since the path is inherited by child processes this is not remotely likely an issue.)
[updated for 2021]
(Regardless if you are on Mac, Linux, or Windows:)
If you are confused about how to start the latest version of python, on most platforms it is the case that python3
leaves your python2
installation intact (due to the above compatibility reasons); thus you can start python3 with the python3
command.
Historically…
The naming convention is that generally, most scripts will call python2 or python3 explicitly. This happened due to a need for backwards compatibility.
Even though technically python doesn’t even guarantee backwards compatibility between minor versions, Python3 really breaks backwards compatibility. At the time, programs invoking ‘python
‘ were expecting python2 (which was the main version at the time). Extremely old systems may have programs and scripts which expect python
=python2, and changing this would break those programs and scripts.
At the time this answer was written, OP should not have changed this due to maintaining compatibility for old scripts.
Circa year 2021…
Nowadays, many years after the python2->python3 transition, most software explicitly refers to python2 or python3 (at least on Linux). For example, they might call #!/usr/bin/env python2
or #!/usr/bin/env python3
. This has for example (python-is-python3-package) freed up the python command to be settable to a user default, but it really depends on the operating system.
The prescription for how distributions should handle the python
command was written up in 2011 as PEP 394 — The «python» Command on Unix-Like Systems. It was last updated in June 2019.
Basically if you are writing a library, you should specify the version of python (2 or 3, or finer-grained under specific circumstances) you can use. Otherwise as an end user, you should feel free to rename this for your own personal use (though your OS or distribution may not make that easy).
Shell alias:
You could, however, make a custom alias in your shell. The way you do so depends on the shell, but perhaps you could do alias py=python3
, and put it in your shell startup file. This will only work on your local computer (as it should), and is somewhat unnecessary compared to just typing it out (unless you invoke the command constantly).
Confused users should not try to create aliases or virtual environments or similar that make python
execute python3
; this is poor form.This is acceptable nowadays, but PEP 394 suggests encouraging users to use a virtualenv instead.
Different 3.* versions, or 2.* versions:
In the extremely unlikely case that if someone comes to this question with two python3 versions e.g. 3.1 vs 3.2, and you are confused that you have somehow installed two versions of python, this is possibly because you have done manual and/or manual installations. You can use your OS’s standard package/program install/uninstall/management facilities to help track things down, and perhaps (unless you are doing dev work that surprisingly is impacted by the few backwards-incompatible changes between minor versions) delete the old version (or do make uninstall
if you did a manual installation). If you require two versions, then reconfigure your $PATH
variable so the ‘default’ version you want is in front; or if you are using most Linux distros, the command you are looking for is sudo update-alternatives
. Make sure any programs you run which need access to the older versions may be properly invoked by their calling environment or shell (by setting up the var PATH
in that environment).
A bit about $PATH
sidenote: To elaborate a bit on PATH: the usual ways that programs are selected is via the PATH
(echo $PATH
on Linux and Mac) environment variable. You can always run a program with the full path e.g. /usr/bin/🔳 some args
, or cd /usr/bin
then ./🔳 some args
(replace blank with the ‘echo’ program I mentioned above for example), but otherwise typing 🔳 some args
has no meaning without PATH
env variable which declares the directories we implicitly may search-then-execute files from (if /usr/bin
was not in PATH
, then it would say 🔳: command not found
). The first matching command in the first directory is the one which is executed (the which
command on Linux and Mac will tell you which sub-path this is). Usually it is (e.g. on Linux, but similar on Mac) something like /usr/bin/python
which is a symlink to other symlinks to the final version somewhere, e.g.:
% echo $PATH
/usr/sbin:/usr/local/bin:/usr/sbin:usr/local/bin:/usr/bin:/bin
% which python
/usr/bin/python
% which python2
/usr/bin/python2
% ls -l /usr/bin/python
lrwxrwxrwx 1 root root 7 Mar 4 2019 /usr/bin/python -> python2*
% ls -l /usr/bin/python2
lrwxrwxrwx 1 root root 9 Mar 4 2019 /usr/bin/python2 -> python2.7*
% ls -l /usr/bin/python2.7
-rwxr-xr-x 1 root root 3689352 Oct 10 2019 /usr/bin/python2.7*
% which python3
/usr/bin/python3
% ls -l /usr/bin/python3
lrwxrwxrwx 1 root root 9 Mar 26 2019 /usr/bin/python3 -> python3.7*
% ls -l /usr/bin/python3.7
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7*
% ls -l /usr/bin/python*
lrwxrwxrwx 1 root root 7 Mar 4 2019 /usr/bin/python -> python2*
lrwxrwxrwx 1 root root 9 Mar 4 2019 /usr/bin/python2 -> python2.7*
-rwxr-xr-x 1 root root 3689352 Oct 10 2019 /usr/bin/python2.7*
lrwxrwxrwx 1 root root 9 Mar 26 2019 /usr/bin/python3 -> python3.7*
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7*
lrwxrwxrwx 1 root root 33 Apr 2 2019 /usr/bin/python3.7-config -> x86_64-linux-gnu-python3.7-config*
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7m*
lrwxrwxrwx 1 root root 34 Apr 2 2019 /usr/bin/python3.7m-config -> x86_64-linux-gnu-python3.7m-config*
lrwxrwxrwx 1 root root 16 Mar 26 2019 /usr/bin/python3-config -> python3.7-config*
lrwxrwxrwx 1 root root 10 Mar 26 2019 /usr/bin/python3m -> python3.7m*
lrwxrwxrwx 1 root root 17 Mar 26 2019 /usr/bin/python3m-config -> python3.7m-config*
sidenote2: (In the rarer case a python program invokes a sub-program with the subprocess
module, to specify which program to run, one can modify the paths of subprocesses with sys.path
from the sys module or the PYTHONPATH
environment variable set on the parent, or specifying the full path… but since the path is inherited by child processes this is not remotely likely an issue.)
[updated for 2021]
(Regardless if you are on Mac, Linux, or Windows:)
If you are confused about how to start the latest version of python, on most platforms it is the case that python3
leaves your python2
installation intact (due to the above compatibility reasons); thus you can start python3 with the python3
command.
Historically…
The naming convention is that generally, most scripts will call python2 or python3 explicitly. This happened due to a need for backwards compatibility.
Even though technically python doesn’t even guarantee backwards compatibility between minor versions, Python3 really breaks backwards compatibility. At the time, programs invoking ‘python
‘ were expecting python2 (which was the main version at the time). Extremely old systems may have programs and scripts which expect python
=python2, and changing this would break those programs and scripts.
At the time this answer was written, OP should not have changed this due to maintaining compatibility for old scripts.
Circa year 2021…
Nowadays, many years after the python2->python3 transition, most software explicitly refers to python2 or python3 (at least on Linux). For example, they might call #!/usr/bin/env python2
or #!/usr/bin/env python3
. This has for example (python-is-python3-package) freed up the python command to be settable to a user default, but it really depends on the operating system.
The prescription for how distributions should handle the python
command was written up in 2011 as PEP 394 — The «python» Command on Unix-Like Systems. It was last updated in June 2019.
Basically if you are writing a library, you should specify the version of python (2 or 3, or finer-grained under specific circumstances) you can use. Otherwise as an end user, you should feel free to rename this for your own personal use (though your OS or distribution may not make that easy).
Shell alias:
You could, however, make a custom alias in your shell. The way you do so depends on the shell, but perhaps you could do alias py=python3
, and put it in your shell startup file. This will only work on your local computer (as it should), and is somewhat unnecessary compared to just typing it out (unless you invoke the command constantly).
Confused users should not try to create aliases or virtual environments or similar that make python
execute python3
; this is poor form.This is acceptable nowadays, but PEP 394 suggests encouraging users to use a virtualenv instead.
Different 3.* versions, or 2.* versions:
In the extremely unlikely case that if someone comes to this question with two python3 versions e.g. 3.1 vs 3.2, and you are confused that you have somehow installed two versions of python, this is possibly because you have done manual and/or manual installations. You can use your OS’s standard package/program install/uninstall/management facilities to help track things down, and perhaps (unless you are doing dev work that surprisingly is impacted by the few backwards-incompatible changes between minor versions) delete the old version (or do make uninstall
if you did a manual installation). If you require two versions, then reconfigure your $PATH
variable so the ‘default’ version you want is in front; or if you are using most Linux distros, the command you are looking for is sudo update-alternatives
. Make sure any programs you run which need access to the older versions may be properly invoked by their calling environment or shell (by setting up the var PATH
in that environment).
A bit about $PATH
sidenote: To elaborate a bit on PATH: the usual ways that programs are selected is via the PATH
(echo $PATH
on Linux and Mac) environment variable. You can always run a program with the full path e.g. /usr/bin/🔳 some args
, or cd /usr/bin
then ./🔳 some args
(replace blank with the ‘echo’ program I mentioned above for example), but otherwise typing 🔳 some args
has no meaning without PATH
env variable which declares the directories we implicitly may search-then-execute files from (if /usr/bin
was not in PATH
, then it would say 🔳: command not found
). The first matching command in the first directory is the one which is executed (the which
command on Linux and Mac will tell you which sub-path this is). Usually it is (e.g. on Linux, but similar on Mac) something like /usr/bin/python
which is a symlink to other symlinks to the final version somewhere, e.g.:
% echo $PATH
/usr/sbin:/usr/local/bin:/usr/sbin:usr/local/bin:/usr/bin:/bin
% which python
/usr/bin/python
% which python2
/usr/bin/python2
% ls -l /usr/bin/python
lrwxrwxrwx 1 root root 7 Mar 4 2019 /usr/bin/python -> python2*
% ls -l /usr/bin/python2
lrwxrwxrwx 1 root root 9 Mar 4 2019 /usr/bin/python2 -> python2.7*
% ls -l /usr/bin/python2.7
-rwxr-xr-x 1 root root 3689352 Oct 10 2019 /usr/bin/python2.7*
% which python3
/usr/bin/python3
% ls -l /usr/bin/python3
lrwxrwxrwx 1 root root 9 Mar 26 2019 /usr/bin/python3 -> python3.7*
% ls -l /usr/bin/python3.7
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7*
% ls -l /usr/bin/python*
lrwxrwxrwx 1 root root 7 Mar 4 2019 /usr/bin/python -> python2*
lrwxrwxrwx 1 root root 9 Mar 4 2019 /usr/bin/python2 -> python2.7*
-rwxr-xr-x 1 root root 3689352 Oct 10 2019 /usr/bin/python2.7*
lrwxrwxrwx 1 root root 9 Mar 26 2019 /usr/bin/python3 -> python3.7*
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7*
lrwxrwxrwx 1 root root 33 Apr 2 2019 /usr/bin/python3.7-config -> x86_64-linux-gnu-python3.7-config*
-rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7m*
lrwxrwxrwx 1 root root 34 Apr 2 2019 /usr/bin/python3.7m-config -> x86_64-linux-gnu-python3.7m-config*
lrwxrwxrwx 1 root root 16 Mar 26 2019 /usr/bin/python3-config -> python3.7-config*
lrwxrwxrwx 1 root root 10 Mar 26 2019 /usr/bin/python3m -> python3.7m*
lrwxrwxrwx 1 root root 17 Mar 26 2019 /usr/bin/python3m-config -> python3.7m-config*
sidenote2: (In the rarer case a python program invokes a sub-program with the subprocess
module, to specify which program to run, one can modify the paths of subprocesses with sys.path
from the sys module or the PYTHONPATH
environment variable set on the parent, or specifying the full path… but since the path is inherited by child processes this is not remotely likely an issue.)
Перевод статьи «The right and wrong way to set Python 3 as default on a Mac».
Есть несколько способов начать работу с Python 3 на macOS, однако не все они одинаково хороши. Сегодня мы рассмотрим, как правильно настроить среду, не нарушая ничего, встроенного в операционную систему macOS.
1. Установите pyenv
Использование неправильного решения может привести к неверному представлению о том, что выбор загружаемой версии Python зависит от псевдонимов в оболочке.
Как нам перестать заботиться о том, какая версия Python используется по умолчанию? Нужно использовать pyenv. Это инструмент для управления несколькими версиями Python. Он простой и вполне соответствует традициям Unix: предназначен для решения одной задачи, и решает ее хорошо.
Хотя доступны и другие варианты установки, проще всего начать следующим образом:
$ brew install pyenv ? /usr/local/Cellar/pyenv/1.2.10: 634 files, 2.4MB
Теперь давайте установим последнюю версию Python (здесь указана версия 3.7.3, однако на данный момент широко используется версия 3.8 и доступна версия 3.9):
$ pyenv install 3.7.3 python-build: use openssl 1.0 from homebrew python-build: use readline from homebrew Downloading Python-3.7.3.tar.xz... -> https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz Installing Python-3.7.3... ## дальнейший вывод не включен ##
3. Установите глобальное значение по умолчанию
Теперь, когда Python 3 установлен через pyenv, мы хотим установить его как нашу версию по умолчанию (глобально) для сред pyenv:
$ pyenv global 3.7.3 # проверим, сработало ли $ pyenv version 3.7.3 (set by /Users/mbbroberg/.pyenv/version)
Сила pyenv основана на том, что он контролирует путь нашей оболочки. Чтобы он работал правильно, нам нужно добавить следующее в наш файл конфигурации (мы использовали .zshrc, а вам, возможно, подойдет .bash_profile):
$ echo -e 'if command -v pyenv 1>/dev/null 2>&1; thenn eval "$(pyenv init -)"nfi' >> ~/.zshrc
После этой команды наш файл (.zshrc для zsh или .bash_profile для Bash) должен включать следующие строки:
if command -v pyenv 1>/dev/null 2>&1; then eval "$(pyenv init -)" fi
Теперь мы точно знаем, что используем Python 3.7.3, и pip будет обновляться вместе с ним без какой-либо ручной настройки и конфликтов между версиями. Использование менеджера версий (pyenv) позволяет нам легко регулировать будущие обновления, не беспокоясь о том, какую версию Python мы используем в данный момент.
Успешный результат
Освоив этот рабочий процесс, вы сможете использовать pyenv для управления несколькими версиями Python.
Для управления зависимостями также важно использовать виртуальные среды. Тут нам пригодятся такие встроенные библиотеки, как venv и virtualenvwrapper.
Среда выполнения Python
Теперь, когда мы разобрались с версиями Python, можно углубиться в вопрос, почему эта проблема сбивает с толку так много людей.
Версия Python, поставляемая с macOS, сильно устарела по сравнению с тем, что Python рекомендует использовать для разработки. Как отмечает XKCD, размышления о выборе среды выполнения Python иногда могут быть до смешного сложными:
Многие пользователи держат десятки интерпретаторов Python на своих компьютерах, хотя понятия не имеют, как эффективно ими управлять.
Слишком часто люди просто загружают последнюю версию Python, помещают ее в свою переменную $PATH и на этом всё (или используют команду brew install python3
, которая делает примерно то же самое). Это может привести к поломкам и неисправностям, которые будет весьма сложно исправить.
Чего не стоит делать
Можно подумать, что, чтобы сделать Python 3 на macOS версией по умолчанию, нужно заменить старую версию и на новую:
# для начала найдем бинарный файл python $ which python /usr/bin/python # затем переименуем его, задав неиспользуемое имя $ sudo mv /usr/bin/python /usr/bin/python2 # наконец, переместим на предыдущий путь новый бинарный файл $ sudo mv $PATHTOBINARY/python3 /usr/bin/python
Этот шаблон соответствует тому, что обычно делает /usr/bin/ между основными выпусками Python, однако это неправильный ход:
$ sudo mv /usr/bin/python /usr/bin/python2 mv: rename /usr/bin/python to /usr/bin/python2: Operation not permitted
К счастью, macOS не дает сломать систему непродуманными действиями. Дальнейшие исследования вопроса показывают, что описанный выше способ не следует применять.
Что можно попробовать
Теперь, когда мы знаем, чего не следует делать, давайте посмотрим, что сделать можно. Когда мы думаем об общих шаблонах установки приложений в macOS, есть несколько вариантов.
Использовать Python 3 по умолчанию для macOS
На веб-сайте Python есть установщик macOS Python 3, который мы можем загрузить и использовать. Если мы воспользуемся установкой пакета, python3 будет доступен в /usr/local/bin/.
Поскольку двоичный файл Python, хранящийся в /usr/bin/, не может быть изменен, необходимы алиасы (псевдонимы). Что хорошо в псевдониме, так это то, что он специфичен для нашей оболочки командной строки. Поскольку по умолчанию мы используем zsh, мы помещаем в файл .zshrc
следующее:
$ echo "alias python=/usr/local/bin/python3.7" >> ~/.zshrc
Если по умолчанию вы используете оболочку Bash, вы можете добавить следующий текст в свой .bashrc
:
$ echo "alias python=/usr/local/bin/python3.7" >> ~/.bashrc
Эта стратегия работает, но она не идеальна для будущих обновлений Python. Это означает, что нам придется регулярно проверять сайт и загружать новые файлы, поскольку Python не включает в себя способ обновления из командной строки.
Доверить управление Homebrew
Проект Homebrew предоставляет бесплатный менеджер пакетов для macOS, на который полагаются многие люди. Он имеет открытый исходный код. Этот менеджер пакетов дает пользователям Apple возможности, аналогичные возможностям apt-get или yum.
Если вы являетесь пользователем Homebrew, возможно, у вас уже установлен Python. Чтобы быстро проверить это, запустите конвейер команд:
$ brew list | grep python python
Если в качестве результата вы получите python, значит, он установлен. Но какая это версия? Давайте проверим:
$ brew info python python: stable 3.7.3 (bottled), HEAD Interpreted, interactive, object-oriented programming language https://www.python.org/ /usr/local/Cellar/python/3.7.2_1 (8,437 files, 118MB) * ## дальнейший вывод не включен ##
Отлично! Мейнтейнеры Homebrew обновили Python bottle (бинарный пакет), чтобы он указывал на последний релиз. Поскольку мейнтейнеры Homebrew более ответственны в отношении обновления релиза, чем большинство из нас, мы можем использовать версию Python 3 от Homebrew с помощью следующей команды:
$ brew update && brew upgrade python
Теперь нам нужно, чтобы наш алиас указывал на копию Python, которой управляет Homebrew:
# Если вы добавляли предыдущий алиас, используйте текстовый редактор, чтобы обновить строку alias python=/usr/local/bin/python3
Чтобы убедиться, что приведенный выше путь указывает на то место, куда Homebrew установил Python в нашей среде, мы можем запустить brew info python
и поискать информацию о пути.
Этот метод использования Homebrew для управления нашей средой Python является хорошей отправной точкой.
Что делать, если нам все еще нужен Python 2?
Для любого новичка в Python имеет смысл начинать сразу с Python 3. Но те из нас, кому все еще нужен Python 2 – например, для участия в проекте, где есть только Python 2, – могут продолжать использовать версию Python, доступную в macOS по умолчанию (путь — /usr/bin/python):
$ /usr/bin/python >>> print("This runtime still works!") This runtime still works!
Homebrew настолько хорош, что даже предлагает другую формулу для Python 2:
# Если вам нужен Python 2.7, запустите $ brew install python@2
Чтобы вернуться к использованию версии Python, которая установлена в системе по умолчанию, в любой момент можно удалить псевдонимы из файла конфигурации нашей оболочки.
Не забудьте обновить pip до версии pip3!
pip – это дефолтный менеджер пакетов Python. Хотя мы изменили нашу дефолтную команду python на третью версию, нужно также отдельно задать псевдоним нашей команде pip (если у нас предыдущая версия).
Для начала нужно проверить, какая, собственно, у нас версия:
# Обратите внимание, что буква V - заглавная $ pip -V pip 19.0.3 from /Library/Python/2.7/site-packages/pip-19.0.3-py2.7.egg/pip (python 2.7)
Чтобы устанавливать пакеты, наверняка совместимые с нашей новой версией Python, мы используем еще один алиас, указывающий на совместимую версию pip.
Поскольку в данной ситуации мы используем Homebrew в качестве менеджера пакетов, мы знаем, что он установил pip3 при установке Python 3. Путь по умолчанию должен быть таким же, как и в Python 3, но мы можем проверить это, попросив оболочку найти его:
$ which pip3 /usr/local/bin/pip3
Теперь, когда мы точно знаем местоположение, мы добавим его в наш файл конфигурации оболочки, как мы это делали раньше:
$ echo "alias pip=/usr/local/bin/pip3" >> ~/.zshrc # для Bash: $ echo "alias pip=/usr/local/bin/pip3" >> ~/.bashrc
Наконец, мы можем проверить, что запущенный pip указывает на pip3. Для этого нужно открыть новую оболочку или перезагрузить текущую и посмотреть, на сто указывает псевдоним:
# Эта команда перезагружает текущую оболочку без выхода из сессии # Альтернативный вариант - выйти из оболочки и начать новую сессию $ exec $0 # Теперь мы можем посмотреть, куда указывает pip $ which pip pip: aliased to /usr/local/bin/pip3
Мы можем избежать использования Homebrew для обновления pip, но для этого потребуется гораздо более подробное руководство, основанное на документации Python.
Заключение
Если вы только начинаете разработку на Python на macOS, выполните необходимые настройки, чтобы с самого начала использовать правильную версию Python.
Установка Python 3 с Homebrew или без него и использование псевдонима позволят вам начать программировать, но в долгосрочной перспективе это не лучшая стратегия.
Использование pyenv — простое решение для управления версиями. Оно станет отличной отправной точкой.
Python
January 14, 2022January 11, 2022
1 Minute
In this tutorial, I’ll show you how to update your Mac’s default version of Python from 2.x to 3.x.
If Python 3.X is already installed on your system, even if it’s not the default version, then you should be able to run version 3.X using the python3
command in your Terminal. But in this tutorial, I’ll be showing you how you can run version 3.X using the default python
command.
Step 0: Install Homebrew
Homebrew is a very popular package manager for macOS. If you don’t already have it installed, you can install it by running this command:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Step 1: Install Python with Homebrew
This command will Python 3.
brew install python
Step 2:
Next, we’ll check the symlinks for Python 3.x. A symlink or a Symbolic Link is simply enough a shortcut to another file.
ls -l /usr/local/bin/python*
This should output something like the following:
Look at the first line. It shows default python
being symlinked to the brew installed python3
. If it does not show this exactly, then set it as the default python
symlink run the following:
ln -s -f /usr/local/bin/python3 /usr/local/bin/python
You should probably run this command just to be sure. Run ls -l /usr/local/bin/python*
again and make sure you have the desired output.
Step 3: Verify Python 3.X install
Run the following command to see which executable Python binary will launch when you issue a python
command to the shell:
which python
The output should be this: /usr/local/bin/python
Finally, check if the default Python version has changed:
python --version
The terminal should output the newest version of Python 3.x. For me, it is Python 3.9.7
.
That’s it! Hope this helps.
Published
January 14, 2022January 11, 2022
Последнее обновление: 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
можно изменить версию по умолчанию
Irfan
Posted on Dec 4, 2019
• Updated on Jun 10, 2020
By default MacOS ships with Python-2.-. But, I guess most of us have long back started to work with Python-3 and it is very irritating to run python3 every time instead of python in terminal. Here is how to do this.
Open the terminal (bash or zsh) whatever shell you are using.
Install python-3 using Homebrew (https://brew.sh).
brew install python
Enter fullscreen mode
Exit fullscreen mode
Look where it is installed.
ls -l /usr/local/bin/python*
Enter fullscreen mode
Exit fullscreen mode
The output is something like this:
lrwxr-xr-x 1 irfan admin 34 Nov 11 16:32 /usr/local/bin/python3 -> ../Cellar/python/3.7.5/bin/python3
lrwxr-xr-x 1 irfan admin 41 Nov 11 16:32 /usr/local/bin/python3-config -> ../Cellar/python/3.7.5/bin/python3-config
lrwxr-xr-x 1 irfan admin 36 Nov 11 16:32 /usr/local/bin/python3.7 -> ../Cellar/python/3.7.5/bin/python3.7
lrwxr-xr-x 1 irfan admin 43 Nov 11 16:32 /usr/local/bin/python3.7-config -> ../Cellar/python/3.7.5/bin/python3.7-config
lrwxr-xr-x 1 irfan admin 37 Nov 11 16:32 /usr/local/bin/python3.7m -> ../Cellar/python/3.7.5/bin/python3.7m
lrwxr-xr-x 1 irfan admin 44 Nov 11 16:32 /usr/local/bin/python3.7m-config -> ../Cellar/python/3.7.5/bin/python3.7m-config
Enter fullscreen mode
Exit fullscreen mode
Change the default python symlink to the version you want to use from above.
Note that, we only need to choose the one that end with python3.*. Please avoid using the ones’ that end with config or python3.*m or python3.*m-config.
Below command shows how it should be done:
ln -s -f /usr/local/bin/python3.7 /usr/local/bin/python
Enter fullscreen mode
Exit fullscreen mode
Close the current terminal session or keep it that way and instead open a new terminal window (not tab). Run this:
python --version
Enter fullscreen mode
Exit fullscreen mode
You will get this:
Python 3.7.5
Enter fullscreen mode
Exit fullscreen mode
Hah! That’s it. Happy coding!!
I’ve been dipping my toe back into Python development as I get ready to head to PyCon US. (If you’re headed there as well and want to share your Python story, let me know!) When I installed a module to tinker around with, I got a reminder that I needed to install Python 3 soon.
$ pip install todoist-python
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
So, I did what any of us would do and googled around looking for a guide to update my development environment, which runs on Mac (the macOS operating system, formerly known as OS X). To my surprise, I found only a handful of StackOverflow posts, and they pointed me to partial solutions. Here’s the full story of how to set up your environment without breaking anything built into the macOS operating system.
1. Install pyenv
Moshe Zadka cautions that doing this wrong could result in an unreliable idea of which Python is running that depends too closely on shells loading aliases. I knew Moshe was familiar with Python, but what I didn’t know is that he is an author of many Python tutorials as well as an upcoming book on Python development on macOS. He helped 40 colleagues develop Python safely and consistently on macOS systems following one core principle:
«The basic premise of all Python development is to never use the system Python. You do not want the Mac OS X ‘default Python’ to be ‘python3.’ You want to never care about default Python.»
How do we stop caring about the default? Moshe recommends using pyenv to manage Python environments (for a deeper dive on configuring pyenv, see this article). This tool manages multiple versions of Python and is described as «simple, unobtrusive, and follows the Unix tradition of single-purpose tools that do one thing well.»
While other installation options are available, the easiest way to get started is with Homebrew:
$ brew install pyenv
? /usr/local/Cellar/pyenv/1.2.10: 634 files, 2.4MB
2. Install Python
Now let’s install the latest Python version (3.7.3 as of this writing):
$ pyenv install 3.7.3
python-build: use openssl 1.0 from homebrew
python-build: use readline from homebrew
Downloading Python-3.7.3.tar.xz...
-> https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz
Installing Python-3.7.3...
## further output not included ##
3. Set your global default
Now that Python 3 is installed through pyenv, we want to set it as our global default version for pyenv environments:
$ pyenv global 3.7.3
# and verify it worked
$ pyenv version
3.7.3 (set by /Users/mbbroberg/.pyenv/version)
The power of pyenv comes from its control over our shell’s path. In order for it to work correctly, we need to add the following to our configuration file (.zshrc for me, possibly .bash_profile for you):
$ echo -e 'if command -v pyenv 1>/dev/null 2>&1; thenn eval "$(pyenv init -)"nfi' >> ~/.zshrc
After that command, our dotfile (.zshrc for zsh or .bash_profile for Bash) should include these lines:
if command -v pyenv 1>/dev/null 2>&1; then
eval "$(pyenv init -)"
fi
Now we know for certain that we’re using Python 3.7.3 and pip will update alongside it without any manual aliasing between versions. Using Moshe’s recommendation to use a version manager (pyenv) enables us to easily accept future upgrades without getting confused about which Python we are running at a given time.
Success
As you get comfortable with this workflow, you can use pyenv to manage multiple versions of Python. It’s also essential, for dependency management, to use virtual environments. I mention how to use the built in venv library in the article, and Moshe recommends virtualenvwrapper for managing virtual environments.
Understanding Python runtimes
Now that you have your Python versions fixed, it’s safe to explore why this problem confuses so many people.
The version of Python that ships with macOS is well out of date from what Python recommends using for development. Pondering Python runtimes can be comically challenging at times, as noted by XKCD.
Many users have dozens of Python interpreters on their computer already, but have no idea how to manage them effectively. Too often, people just download the latest Python release, move it to their path, and call it a day (or use brew install python3, which would do something similar). This can cause breakages down the line in frustrating ways that can be difficult to troubleshoot.
What NOT to do
My first idea on how to make Python 3 the default Python on my system was to move the old version and add the new one:
# what I thought would work
# first, I'll find my python binary
$ which python
/usr/bin/python
# next, I'll move it to an unused name
$ sudo mv /usr/bin/python /usr/bin/python2
# lastly, I'll move the new binary to the previous path
$ sudo mv $PATHTOBINARY/python3 /usr/bin/python
The pattern followed what /usr/bin/ usually does between major releases of Python, but I quickly learned it was the wrong move:
$ sudo mv /usr/bin/python /usr/bin/python2
mv: rename /usr/bin/python to /usr/bin/python2: Operation not permitted
Thankfully, macOS protected me from breaking something I don’t fully understand. Further research proves this is exactly what we shouldn’t do.
Another thing not to try
Now that we know what not to do, let’s look at what we could do. There are a couple options when we think about common installation patterns for applications on macOS.
Use Python 3 as the macOS default
Python’s website has a macOS Python 3 installer we can download and use. If we use the package installation, a python3 fill will be available in /usr/local/bin/.
Aliasing is a must since the Python binary stored in /usr/bin/ can’t be changed. What’s nice about an alias is that it’s specific to our command-line shell. Since I use zsh by default, I put the following into the .zshrc file:
$ echo "alias python=/usr/local/bin/python3.7" >> ~/.zshrc
If you are using the default Bash shell, you can append this same text to your .bashrc:
$ echo "alias python=/usr/local/bin/python3.7" >> ~/.bashrc
This strategy works, but it isn’t ideal for making future updates to Python. It means we have to remember to check the website and download the new files since Python doesn’t include a command-line way to update.
Have Homebrew manage Python 3
The Homebrew project provides a free and open source package manager for macOS that many people rely on. It gives Apple users a power similar to apt-get or yum. If you are a Homebrew user, you may already have Python installed. To quickly check, run:
$ brew list | grep python
python
If Python shows up under the command, it’s installed. What version is it? Let’s check:
$ brew info python
python: stable 3.7.3 (bottled), HEAD
Interpreted, interactive, object-oriented programming language
https://www.python.org/
/usr/local/Cellar/python/3.7.2_1 (8,437 files, 118MB) *
## further output not included ##
Okay, great! The Homebrew maintainers have updated the default Python bottle to point to the latest release. Since the Homebrew maintainers are more dependable at updating the release than most of us, we can use Homebrew’s version of Python 3 with the following command:
$ brew update && brew upgrade python
Now we want to point our alias (from above) to the copy of Python that Homebrew manages:
# If you added the previous alias, use a text editor to update the line to the following
alias python=/usr/local/bin/python3
To make sure the path above points to where Homebrew installed Python in our environment, we can run brew info python and look for the path information.
This method, of using Homebrew to manage our Python environment, is a good starting place, and it made sense to me at the time.
What if we still need Python 2?
It makes sense for anyone new to Python to begin with Python 3. But those of us who still need Python 2—for example, to contribute to a Python project that’s only available in Python 2—can continue to use the default macOS Python binary available in /usr/bin/python:
$ /usr/bin/python
>>> print("This runtime still works!")
This runtime still works!
Homebrew is so wonderful, it even offers a different formula for Python 2:
# If you need Homebrew's Python 2.7 run
$ brew install python@2
At any time, we can remove the aliases from our shell’s configuration file to go back to using the default copy of Python on the system.
Don’t forget to update pip to pip3!
The pip command is the default package manager specifically for Python packages. Although we changed our default Python command to be version 3, we have to alias our pip command separately if it’s on the previous version. First, we need to check what version we’re on:
# Note that this is a capital V (not lowercase)
$ pip -V
pip 19.0.3 from /Library/Python/2.7/site-packages/pip-19.0.3-py2.7.egg/pip (python 2.7)
To ensure we’re installing packages compatible with our new version of Python, we’ll use another alias to point to the compatible version of pip. Since we’re using Homebrew as our package manager in this situation, we know it installed pip3 when we installed Python 3. The default path should be the same as Python 3, but we can confirm this by asking the shell to find it:
$ which pip3
/usr/local/bin/pip3
Now that we know the location, we will add it to our shell configuration file, as we did before:
$ echo "alias pip=/usr/local/bin/pip3" >> ~/.zshrc
# or for Bash
$ echo "alias pip=/usr/local/bin/pip3" >> ~/.bashrc
Last, we can confirm that running pip points to pip3 by opening a new shell or by resetting our current shell and seeing what we point to:
# This command reloads the current shell without exiting the session
# Alternatively, exit the shell and start a new one
$ exec $0
# Now we can look to see where pip points us
$ which pip
pip: aliased to /usr/local/bin/pip3
We can avoid using Homebrew to update pip, but that requires a much longer tutorial from the Python documentation.
Do it right from the start
If you are just getting started with Python development on a macOS, do the necessary configurations to make sure you’re using the right version of Python from the start. Installing Python 3, with or without Homebrew, and using alias will let you start coding, but it’s not a good strategy for the long run. Using pyenv as a simple version management solution to get you off to a good start.
This article was originally published in May 2019 and has been updated by the editor.