Как скачать и установить Python на Mac OC X
Это краткий туториал покажет вам, как правильно установить Python 3 на Mac OS X. Существует несколько способов установки Python 3, включая скачивание с [официального сайта Python] (https://www.python.org/downloads/), однако я настоятельно рекомендую вместо этого использовать менеджер пакетов, такой как Homebrew для управления всеми вашими зависимостями в будущем. Это сделает вашу жизнь намного проще.
Какая версия python установлена по умолчанию
Хотя Python 2 установлен по умолчанию на компьютерах Apple, Python 3 — нет. Вы можете проверить это, набрав в Терминале python —version и нажав return:
Чтобы проверить, установлен ли Python 3, попробуйте запустить команду python3 —version . Скорее всего, вы увидите сообщение об ошибке, но стоит проверить. Даже если у вас есть версия Python 3, мы обновим ее до самой последней версии, которая на данный момент в 2019 году 3.7.2.
Установка Xcode и Homebrew
Мы будем использовать менеджер пакетов Homebrew для установки Python 3 — это общая практика. Homebrew необходим пакет Xcode Apple, поэтому для его установки выполните следующую команду:
Нажимайте далее или подтвердить (Xcode — большая программа, ее установка может занять некоторое время).
Далее установите Homebrew:
Чтобы проверить правильность установки Homebrew, выполните следующую команду:
Установка Python 3 на MAC OC X
Чтобы скачать и установить последнюю версию Python, выполните следующую команду:
Подождите пока установятся все зависимости и сам python 3
Теперь давайте подтвердим, какая версия установилась:
Что бы писать код Python 3 из командной строки, введите python3:
Если вы хотите выйти, введите exit() и return или Ctrl-D (одновременно клавиши Control и D).
Что бы запустить оболочку Python 2, просто вводите python :
[Бонус] Первый код в IDLE python для новичков
Теперь Python 3 установлен на ваш Mac, пора приступить к конкретному написанию первого кода. В Python большинство команд основано на контекстных словах в английском языке. Если в C# потребовалось бы ввести команду Console.WriteLine , чтобы вывести запись на экран, в Python это простая команда print .
Я покажу 3 простые задачи, которые есть в каждом коде:
- вывод данных
- операция сложения
- использование условного оператора if
Для нашей первой задачи мы будем использовать IDLE. Это простой редактор кода, поставляется вместе с Python при его установке. Воспользуйтесь поиском и откройте IDLE.
Откроется окно, которое мы называем “оболочкой”. Там отображается результат выполнения кода, но писать код мы будем отдельно. Для этого нам нужно создать новый файл. Мы можем сделать это, нажав File > New File в верхнем меню. Откроется новый пустой файл.
Сохраните файл. Выберите File > Save As , затем сохраните его как helloworld.py . Обычно, в качестве первой программы используют вывод «Hello World» на экран.
Команда, которую мы собираемся использовать, является командой вывода данных в оболочку. Эта команда выглядит следующим образом. В скобках в кавычках находится текст, который мы выведем на экран.
После того, как вы ввели этот код в файл , выберите File > Save в меню, чтобы сохранить обновленную программу, а затем нажмите Run > Run Module из меню. Ваш вывод появится в окне оболочки. Это должно выглядеть примерно так.
Попробуйте распечатать разные фразы на экране, чтобы привыкнуть к коду.
Наша вторая задача — заставить Python считать за нас. Создайте новый файл Calculation.py. На этот раз мы выведем результат сложения двух чисел. Прибавим 9 к 8, для этого нам нужно ввести в наш новый файл команду print , которая выглядит следующим образом.
Как только вы это сделаете, нужно сохранить и затем запустить программу, нажав Run > Run Module . В оболочке появится результат вычислений, вот так:
Попробуйте различные вычисления, чтобы привыкнуть, помните, что вокруг чисел не нужны кавычки. Если вы еще не знакомы с операторами python, рекомендую прочить эту статью.
Наконец, мы создадим еще одну базовую программу, которая будет выводить результат в зависимости от входных данных, с помощью оператора if . Давайте снова откроем новый файл и выпишем следующий синтаксис:
Здесь мы объявляем переменную my_number равную 100, затем создаем конструкцию if-else , чтобы проверить, больше ли my_number числа 50. Если утверждение верно, мы получим «Это большое число», в противном случае мы увидим «Это небольшое число». ». Не забудьте сохранить и запустить программу, как вы это делали в предыдущих примерах.
Вы заметите, что программа печатает «Это большое число», потому что наш номер превышает 50. Попробуйте поменять номер и посмотрите, какой результат получите. Например, что выведет скрипт, если my_number = 50 ?
Записки на полях
Грабли, на которые я наступил
суббота, 22 февраля 2020 г.
Python на MacOS. Смена версии по умолчанию на 3.8 (или любую последнюю)
Выясняем, какие у нас есть версии, и какая версия выбрана основной
$ python -V
Python 2.7.10
$ python3 -V
Python 3.8.1
Видно, что есть как минимум 2 версии (на самом деле еще есть 3.7) Python. Версия по умолчанию — 2.7. Выясняем пути к интерпретаторам
$ which python
/usr/bin/python
$ which python3
/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
Путь к python3 надо сохранить. Он нам потребуется. Открывает файл настроек bash:
$ nano
В самый низ добавляем строку:
alias python=python3
это, если команда python3 вызывает последнюю версию интерпреатора, а не предыдущую (3.7). Или полный путь:
alias python=»/Library/Frameworks/Python.framework/Versions/3.8/bin/python3″
Сохраняем файл. Далее команда:
$source
Закрываем все терминальные окна. Не сворачиваем «крестиком», а закрываем через Command-Q. Заново открываем терминал и проверяем:
$ python -V
Python 3.8.1
Должна быть правильная версия интерпретатора.
How to set Python’s default version to 3.x on OS X?
I’m running Mountain Lion and the basic default Python version is 2.7. I downloaded Python 3.3 and want to set it as default.
How do I set it so that every time I run $ python it opens 3.3?
21 Answers 21
Changing the default python executable’s version system-wide could break some applications that depend on python2.
However, you can alias the commands in most shells, Since the default shells in macOS (bash in 10.14 and below; zsh in 10.15) share a similar syntax. You could put alias python=’python3′ in your
/.profile , and then source
/.bash_profile and/or your
/.zsh_profile with a line like:
This way, your alias will work across shells.
With this, python command now invokes python3 . If you want to invoke the «original» python (that refers to python2) on occasion, you can use command python , which will leaving the alias untouched, and works in all shells.
If you launch interpreters more often (I do), you can always create more aliases to add as well, i.e.:
Tip: For scripts, instead of using a shebang like:
This way, the system will use python3 for running python executables.
/.bash_profile instead of
/.bash_aliases? – UnsettlingTrend Jul 2 ’16 at 23:30
/.bash_profile. – Haymaker87 Jul 26 ’16 at 15:41
/.bash_profile after edit
/.bash_profile file. – Wei Lu Aug 1 ’16 at 22:08
You can solve it by symbolic link.
Then put the alias as follows:
Now save the file and then run the
Congratulation . Now, you can use python3 by typing python.
/.bash_profile, alias pip=’pip3′, source
/.bash_profile, pip —version – SnellyBigoda Jan 13 at 21:37
/.bash_profile everytime I re-opened my terminal? It reverts to python2 once I close and open the terminal again. – Ricky Aguilar Apr 21 at 2:46
Go to terminal type:
This will setup default python as python3.x
I’m a little late to the game on this one, but I thought I should post an updated answer since I just encountered this issue for myself. Please note that this will only apply to a Mac-based setup (I haven’t tried it with Windows or any flavor of Linux).
The simplest way to get this working is to install Python via Brew. If you don’t have brew installed, you will need to do that first. Once installed, do the following in at the terminal:
This will install Python 3. After it’s installed, run this:
You will see all of the links created by brew to its Python install. It will look something like this:
The first row in this example shows the python3 symlink. To set it as the default python symlink run the following:
Once set, you can do:
and it should show:
You will have to reload your current terminal shell for it to use the new symlink in that shell, however, all newly opened shell sessions will (should) automatically use it. To test this, open a new terminal shell and run the following:
The following worked for me
This worked for me. I added alias and restarted my terminal:
Go to ‘Applications’, enter ‘Python’ folder, there should be a bash script called ‘Update Shell Profile.command’ or similar. Run that script and it should do it.
Update: It looks like you should not update it: how to change default python version?
I believe most of people landed here are using ZSH thorugh iterm or whatever, and that brings you to this answer.
You have to add/modify your commands in
I’m not sure if this is available on OS X, but on linux I would make use of the module command. See here.
Set up the modulefile correctly, then add something like this to your rc file (e.g.
This will make it so that your paths get switched around as required when you log in without impacting any system defaults.
I think when you install python it puts export path statements into your
/.bash_profile file. So if you do not intend to use Python 2 anymore you can just remove that statement from there. Alias as stated above is also a great way to do it.
Here is how to remove the reference from
/.bash_profile — vim ./.bash_profile — remove the reference (AKA something like: export PATH=»/Users/bla/anaconda:$PATH») — save and exit — source ./.bash_profile to save the changes
In this article author discuss three ways of setting default python:
- What NOT to do.
- What we COULD do (but also shouldn’t).
- What we SHOULD do!
All these ways are working. You decide which is better.
Suggestions to alias python to python3 will cause problems with virtual environments that set the version of python (eg: pyenv). With pyenv, you can set the version globally like so:
and then in any specific project, you can create a .python-version file which has the python version inside of it:
This is the best way to manage multiple versions of python on a system in my opinion.
If you are using a virtualenvwrapper , you can just locate it using which virtualenvwrapper.sh , then open it using vim or any other editor then change the following
Change the line VIRTUALENVWRAPPER_PYTHON=»$(command \which python)» to VIRTUALENVWRAPPER_PYTHON=»$(command \which python3)» .
For me the solution was using PyCharm and setting the default python version to the the one that i need to work with.
install PyCharm and go to file ==> preferences for new project, then choose the interpreter you want for your projects, in this case python 3.3
If you are using macports, that has a easier way to do:
port install python37
after install, set default:
sudo port select —set python python37
sudo port select —set python3 python37
restart your cmd window, finished.
Well. It’s kinda old. But still deserves a good answer.
And the good one is You Don’t Wanna Touch The Default Python On Mac.
Install any Python version you need via Homebrew or whatever and use it in virtualenv. Virtualenv is often considered to be something crap-like, but it’s still way, wayyyy better than changing python version system-wide (macOS is likely to protect itself from such actions) or user-wide, bash-wide. whatever. Just forget about the default Python. Using playgrounds like venv is what your OS will be most, very most grateful for.
The case is, for example, many modern Linux distributions get rid of Python2 installed out-of-the-box, leaving only Python3 in the system. But everytime you try to install something old with python2 as a dependency. hope you understand what I mean. A good developer doesn’t care. Good developers create clean playgrounds with python version they desire.