- How to Update Python on Mac?
- How to install Python 3 in macOS with Installer
- How to install Python 3 using Homebrew
- How to Find out the Installed Version of Python
- How to Install Python 3 on Mac – Brew Install Update Tutorial
- A Single Command to Run Python 3
- How to Install Homebrew on Mac
- How to Install pyenv to Manage Your Python Versions
- How to Use pyenv to Install Python or Update Your Python Version
- Troubleshooting pyenv Installation
- How to Set Up Your MacOS PATH for pyenv (Bash or ZSH)
- How to Set a Version of Python to Global Default (Bash or ZSH)
- The Final Step: Close Your Terminal and Restart it
- Обновление Python на Mac
- 14 ответов
How to Update Python on Mac?
Python is a popular programming language that is widely used by both beginners and professional developers. Modern versions of Mac OS support Python 2.7.x (or Python 2.6.1 in older versions), but many users need to upgrade to Python 3.6 or 3.7.
Today I will explain how to install the Python 3 update on a Mac in two different ways.
Note that I mean “install update” rather than “upgrade”, since Python 2 will remain on the Mac with this method. Some Mac programs require Python 2, and when upgrading they may start to malfunction or stop working altogether. Therefore, we will not update the installed version, but install Python 3 in parallel. Python 3 and Python 2 can coexist on the same Mac without conflicts, just the commands will differ slightly.
How to install Python 3 in macOS with Installer
The easiest way is to download the Python installer from the python.org website.
- Visit Python.org and download the latest available Python installer file;
- Run the downloaded file and install Python 3.x on Mac.
- Python 3.6.x requires about 100MB of available disk space. The installation process is very fast;
- When Python 3 is installed, you will see the Python3 folder in /Applications on your Mac. You will also see IDLE in the /Applications.
Next method will show you how to install Python 3.x on a Mac through Homebrew.
How to install Python 3 using Homebrew
Installing an updated version of Python 3 through Homebrew is extremely simple. Of course, Homebrew should be installed on your computer, however, if you are interested in this method, then you probably have already used the program more than once.
If you haven’t Homebrew in your system, you can take script for Homebrew installing here. This script installs Homebrew to /usr/local so that you don’t need “sudo” when you brew install. It is a careful script; it can be run even if you have stuff installed to /usr/local already. It tells you exactly what it will do before it does it too. You have to confirm everything it will do before it starts.
Now to install Python 3 via Homebrew, run the following command in Terminal:
When Python 3 is installed on a Mac, you can start the program with:
In any case, after installing Python 3 on a computer, the version of Python 2.7 will still remain on it, and you will be able to use it.
How to Find out the Installed Version of Python
Open the Terminal program and use the following command:
In most cases, Python 2.7.x will be installed on macOS: either 2.7.4 or 2.7.10.
If you installed the Python update, you can check the version with the following command:
Once again, both versions of Python can coexist without conflicts.
Note: Once again, I want to remind you that you do not need to upgrade Python 2.x to Python 3.x, because this can lead to program malfunctions. Just install the updated version in parallel.
It’s the best time to ask questions and give us your feedback in comments.
Hi there! My Name is Vincent Lago! My goal is to share insightful reviews, guides, and manuals for people looking to know more about current solutions for Apple hardware and OS. I have years of technological background knowledge including owning a custom iMacs & PCs which was using for different types of business. And now, I want to share my experience with you.
Источник
How to Install Python 3 on Mac – Brew Install Update Tutorial
MacOS comes with Python pre-installed. But it’s Python Version 2.7, which is now deprecated (abandoned by the Python developer community).
The entire Python community has now moved on to using Python 3.x (the current version as of writing this is 3.9). And Python 4.x will be out soon, but it will be completely backward compatible.
If you try to run Python from your MacOS terminal, you’ll even see this warning:
WARNING: Python 2.7 is not recommended. This version is included in macOS for compatibility with legacy software. Future versions of macOS will not include Python 2.7. Instead, it is recommended that you transition to using ‘python3’ from within Terminal.
Until Apple decides to set Python 3.x, as the default you’re going to have to install it yourself.
A Single Command to Run Python 3
For some of you reading this, this command may be enough. You can run Python 3 using this command (with the 3 at the end).
If that’s all you came for, no worries. Have a fun day and happy coding.
But if you want a proper Python version control system to keep track of various versions – and have fine-grain control over which version you use – this tutorial will show you exactly how to accomplish this.
By the way, if you’re wondering why I keep referring to Python 3.x – the x is a stand-in for sub-versions (or point releases as developers call them.) This means any version of Python 3.
How to Install Homebrew on Mac
First you need to install Homebrew, a powerful package manager for Mac.
Open up your terminal. You can do this by using MacOS spotlight (command+space) and typing «terminal».
Now that you’re in a command line, you can install the latest version of Homebrew by running this command:
Your terminal will ask for Super User-level access. You will need to type your password to run this command. This is the same password you type when you log into your Mac. Type it and hit enter.
A screenshot of my heavily customized terminal. Your terminal will probably look different from this.
Homebrew will ask you to confirm you want to install the following. You have to press enter to continue. (Or press any other key if you get cold feet.)
How to Install pyenv to Manage Your Python Versions
Now let’s take a moment to install PyEnv. This library will help you switch between different versions of Python (in case you need to run Python 2.x for some reason, and in anticipation of Python 4.0 coming).
Run this command:
PyEnv installing
Now you can install the latest version of Python.
How to Use pyenv to Install Python or Update Your Python Version
Now you just need to run the following command:
Note that you can substitute 3.9.2 for whatever the latest version of Python is. For example, once Python 4.0.0 comes out, you can run this:
Troubleshooting pyenv Installation
If you encounter an error that «C compiler cannot create executables» then the simplest way to solve this is to reinstall Apple’s Xcode.
Xcode is a tool created by Apple that includes all the C libraries and other tools that Python uses when it runs on MacOS. Xcode is a whopping 11 gigabytes, but you’ll want to be up-to-date. You may want to run this while you’re sleeping.
You can get the latest version of Apple’s Xcode here. I had to do this after upgrading to MacOS Big Sur, but once I did, all the following commands worked fine. Just re-run the above pyenv install 3.9.2 and it should now work.
How to Set Up Your MacOS PATH for pyenv (Bash or ZSH)
First you need to update your Unix path to pave a way for PyEnv to be able to interact with your system.
This is a long explanation of how PATH works in MacOS (and Unix), straight from the pyenv GitHub repo.
When you run a command like python or pip , your operating system searches through a list of directories to find an executable file with that name. This list of directories lives in an environment variable called PATH , with each directory in the list separated by a colon:
Directories in PATH are searched from left to right, so a matching executable in a directory at the beginning of the list takes precedence over another one at the end. In this example, the /usr/local/bin directory will be searched first, then /usr/bin , then /bin .
And here is their explanation of what a Shim is. I’m quoting them at length again because I really can’t explain this better myself.
pyenv works by inserting a directory of shims at the front of your PATH :
Through a process called rehashing, pyenv maintains shims in that directory to match every Python command across every installed version of Python— python , pip , and so on.
Shims are lightweight executables that simply pass your command along to pyenv.
Here’s how to update your .bash_profile in Bash (which is installed in MacOS by default):
Or if you’ve installed ZSH (or OhMyZSH) like I have, you’ll want to edit the .zshrc file instead:
Then you want to add PyEnv Init to your terminal. Run this command if you’re using Bash (again, this is the default with MacOS):
Or run this command if you’re using ZSH:
Now reset your terminal by running this command:
How to Set a Version of Python to Global Default (Bash or ZSH)
You can set the latest version of Python to be global, meaning it will be the default version of Python MacOS uses when you run Python applications.
Run this command:
Again, you can replace 3.9.2 with whatever the latest version is.
Now you can verify that this worked by checking the global version of Python:
You should see this output:
The * means that version is now the global default
The Final Step: Close Your Terminal and Restart it
Once you’ve restarted your browser, you run the python command and you’ll launch the new version of Python instead of the old one.
Yay. Python 3.9.2 and no deprecation warnings
Congratulations. Thank you for reading this, and happy coding.
The teacher who founded freeCodeCamp.org.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives and help pay for servers, services, and staff.
Источник
Обновление Python на Mac
Я хотел обновить мой python 2.6.1 до 3.x на Mac, но мне было интересно, возможно ли это сделать с помощью терминала, или мне нужно скачать установщик с сайта python?
Причина, по которой я задаю этот вопрос, заключается в том, что установщик не обновляет мою версию терминала Python.
14 ответов
Python по умолчанию на OS X не должен быть испорчен, поскольку он используется самой ОС. Если по умолчанию стоит 2.6.1, то у вас должен быть Snow Leopard.
Сначала установите Homebrew (отсутствующий менеджер пакетов для macOS), если у вас нет: введите это в свой терминал
/usr/bin/ruby -e «$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)»
Теперь вы можете обновить ваш Python до Python 3 этой командой
brew install python3 && cp /usr/local/bin/python3 /usr/local/bin/python
Python 2 и python 3 могут сосуществовать, чтобы открыть python 3, введите python3 вместо python
Это самый простой и лучший способ.
Всегда лучше использовать homebrew для обновления или установки python. В типе терминала:
Это установит homebrew (это займет некоторое время в зависимости от скорости вашего интернета)
Затем в терминале введите
Это сначала обновит brew (вам не нужно делать это, если у вас уже есть последняя версия)
Этот напиток обновит python до последней жизнеспособной версии.
Это должно сработать.
Вы также можете использовать:
Установи клик через менеджер пакетов homebrew. Это самый простой и легкий способ.
- Если у вас не установлен homebrew, введите эту команду в своем терминале
- Следующее «brew install awscli»
Это установит aws cli на ваш Mac
Повторяю выше, не возиться с установкой OS X. Столкнулся с парой переустановок, думая, что смогу побить систему. 3.1 install Скотт Гриффитс, предложенный выше, отлично работает с Yosemite, для любых бета-тестеров. Yosemite имеет Python 2.7.6 как часть установки ОС, и ввод «python3.1» из терминала запускает Python 3.1. То же самое для Python 3.4 (установите здесь ) .
Я хотел добиться того же сегодня. Mac с Snow Leopard поставляется с версией Python 2.6.1.
Поскольку несколько версий Python могут сосуществовать, я загрузил Python 3.2.3 с: http://www.python.org/getit /
После установки более новый Python будет доступен в папке «Приложение», а в среде IDE используется версия Python 3.2.3.
Из оболочки python3 работает с более новой версией. Это служит цели 🙂
Эта статья помогла мне сделать правильный выбор, поскольку Mac 10.14.6 по умолчанию поставлялся с Python 2.7 *, и мне пришлось обновиться до 3.7. *
Я считаю, что Python 3 может сосуществовать с Python 2. Попробуйте вызвать его, используя «python3» или «python3.1». Если это не удается, вам может потребоваться удалить 2.6 перед установкой 3.1.
У меня была та же проблема, но потом, после небольшого исследования, я попытался
Появится предупреждающее сообщение о том, что python 3.7.0 . уже установлен, но не связан так что наберите команду brew link python и нажмите Enter, и вы надеетесь, что все будет хорошо для вас
Лично я не стал бы возиться с питоном OSX, как они сказали. Лично я предпочитаю такие вещи, как использование MacPorts и установку нужных версий через командную строку. MacPorts помещает все в отдельное направление (я полагаю, в / opt), поэтому он не переопределяет обычную систему и не мешает ей напрямую. Он имеет все обычные функции любых утилит управления пакетами, если вы знакомы с дистрибутивами Linux.
Я бы также предложил установить python_select через MacPorts и использовать его, чтобы выбрать, какой python вы хотите «активировать» (он изменит символические ссылки, чтобы указать на нужную версию). Таким образом, вы можете в любой момент вернуться к поддерживаемой Apple версии python, поставляемой с OSX, или к любой, установленной через MacPorts.
Оба Python 2x и 3x могут оставаться установленными в MAC. Mac поставляется с Python 2x версии. Чтобы проверить версию Python по умолчанию в вашем MAC, откройте терминал и введите
Однако, чтобы проверить, если вы уже установили любую из версий Python 3x, вам нужно набрать
Если вы этого не сделаете, то установите его вместе с установщиком. Перейдите на официальный сайт питона (https://www.python.org/downloads/), загрузите Последняя версия
И установите его.
Теперь перезапустите терминал и проверьте снова обеими командами:
Надеюсь это поможет.
Python 2.7 и 3 могут сосуществовать.
Версия Python для терминала — 2.7, но вы можете вызвать ее, используя «python3», смотрите это:
Источник