This one will solve all your problems not only on Mac but
to find it on Linux also ( & every basic shell).
TL;DR (you don’t have to go through all the answer – just the 1st half).
LET’S GO
Run in terminal:
which python3
On Mac you should get:
/usr/local/bin/python3
WAIT!!! It’s prob a symbolic link, how do you know? Run:
ls -al /usr/local/bin/python3
and you’ll get (if you’ve installed Python w/ Brew):
/usr/local/bin/python3 -> /usr/local/Cellar/python/3.6.4_4/bin/python3
which means that your
/usr/local/bin/python3
is actually pointing to (the real location)
/usr/local/Cellar/python/3.6.4_4/bin/python3
That’s it!
Longer version (optional):
If for some reason, your
/usr/local/bin/python3
is not pointing to the place you want, which is in our case:
/usr/local/Cellar/python/3.6.4_4/bin/python3
just back it up (+cool trick to add .orig
suffix to file):
cp /usr/local/bin/python3{,.orig}
and run:
rm -rf /usr/local/bin/python3
now create a new symbolic link:
ln -s /usr/local/Cellar/python/3.6.4_4/bin/python3 /usr/local/bin/python3
and now your
/usr/local/bin/python3
is pointing to
/usr/local/Cellar/python/3.6.4_4/bin/python3
Check it out by running:
ls -al /usr/local/bin/python3
I know that mac-OS comes with an old version of Python. I can’t remember how to access it on the Terminal. I’m pretty sure that I installed a newer version of Python on my mini. It doesn’t show up in Applications. When I type the command in Terminal to start the new version of Python, the Terminal can’t find the file. What is the path? Is a new version of Python installed in a different folder every time that I update Python? Is there a search command in Terminal to look for Python? How do I delete Python, including the 1 that comes with mac-OS?
Mac mini,
macOS High Sierra (10.13)
Posted on Apr 18, 2018 11:35 AM
I followed the instruction on the Python Crash Course: A Hands-On Project-Based Introduction by Eric Matthes to configure Sublime Text for Python 3 on Page 9.
$ type -a python3
python3 is /usr/local/bin/python3
Here is the instruction on the book:
I encounter the following problems.
-
Could someone explain every details of the command “$ type -a python3”, especially the sign “$”, and what does this command mean? Because when I type this command in the IDLE, it returns
SyntaxError: invalid syntax
to me, and when I type it in the Terminal, it returns
File "<stdin>", line 1 $ type -a Python3 ^ SyntaxError: invalid syntax
to me.
-
Then I tried to launch Python Launcher and I find the full path of the interpreter. Then I followed the command to build a new system. But when I built the command
print("Hello World")
, it returns/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6: can't find '__main__' module in '' [Finished in 0.1s with exit code 1] [cmd: ['/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6', '-u', '']] [dir: /Applications/Sublime Text.app/Contents/MacOS] [path: /Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]
to me.
halfer
19.8k17 gold badges98 silver badges185 bronze badges
asked Aug 23, 2018 at 15:17
9
(Posted solution on behalf of the question author).
I attach solutions behind each problem that I encountered.
-
Provided by @meissner : You need to distinguish the difference between commands run on the Python and commands run on the Terminal. Commands with “$” in front should be run on the clean Terminal; otherwise, they are referred to Python commands.
-
The reason for my problem is that I did not save the file first before I ran the command
print("Hello World")
. Once I save the file, even if the file is empty without any command, then the command could be executed normally.
One way to overcome this error is to write the complete directory of the executable file (or its alias) instead of just entering the command name. This, however, is not a very user-friendly approach.
An easier way to avoid this error is to add the executable files’ directory to the PATH variable. This often needs to be done after installing Python.
The complete path of the Python (or Python3) UNIX executable can be added (for OS X 10.8 Mountain Lion and up) by:
-
Opening the Terminal and entering the command:
sudo nano /etc/paths
. Enter your password when prompted to do so. -
A list of directories that are currently a part of the PATH variable will appear. Enter the path of the Python install directory at the end of this list.
-
Press
control + X
to quit and thenY
to save the changes.
Python can now be used directly from the Terminal without having to write its location every time. Try executing the command python --version
to output the default version of Python installed on your system.
Use
python3 --version
to find out the version of Python3.x.
Последнее обновление: 16.12.2022
Установка
Для создания программ на Python нам потребуется интерпретатор. Для его установки перейдем на страницу
https://www.python.org/downloads/ и найдем ссылку на загрузку последней версии языка:
Если текущая ОС – Mac OS, то по адресу https://www.python.org/downloads/ будет предложено
загрузить графический установщик для MacOS. Загрузим, запустим его и выполним пошаговую установку:
Для обращения к интерпретатору Python на MacOS применяется команда python3. Напримерб после установки интерпретатора проверим его версию командой
Первая программа
Сначала определим где-нибудь на жестком диске для скриптов папку python. А в этой папке создадим новый текстовый файл, который
назовем hello.py. По умолчанию файлы с кодом на языке Python, как правило, имеют расширение py.
Откроем этот файл в любом текстовом редакторе и добавим в него следующий код:
name = input("Your name: ") print("Hello, ", name)
Скрипт состоит из двух строк. Первая строка с помощью функции input() ожидает ввода пользователем своего имени. Введенное
имя затем попадает в переменную name
.
Вторая строка с помощью функции print()
выводит приветствие вместе с введенным именем.
Теперь запустим командную строку/терминал и с помощью команды cd перейдем к папке, где находится файл с исходным кодом hello.py (например, в моем случае это папка “/Users/eugene/Documents/python”).
cd /Users/eugene/Documents/python
Далее для выполнения скрипта hello.py передадим его интерпретатору python:
В итоге программа выведет приглашение к вводу имени, а затем приветствие.