- Как скачать и установить Python на Mac OC X
- Какая версия python установлена по умолчанию
- Установка Xcode и Homebrew
- Установка Python 3 на MAC OC X
- [Бонус] Первый код в IDLE python для новичков
- Installing Python 3 on Mac OS X¶
- Doing it Right¶
- Working with Python 3¶
- Pipenv & Virtual Environments¶
- O’Reilly Book
- dineshviswanath / python_web_dev_flask_environment_setup.md
- This comment has been minimized.
- automactic commented Jan 3, 2017
- This comment has been minimized.
- itsgokhanyilmaz commented Jan 28, 2017
- This comment has been minimized.
- LordA98 commented Mar 19, 2017
- This comment has been minimized.
- neozero25 commented Nov 5, 2017
- This comment has been minimized.
- gopaljaiswal commented Nov 10, 2017 •
- This comment has been minimized.
- tubala commented Jan 1, 2018
- This comment has been minimized.
- theblindguidedog commented Jan 25, 2019
- This comment has been minimized.
- horsecoin commented Apr 14, 2019 •
Как скачать и установить 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 ?
Источник
Installing Python 3 on Mac OS X¶
Mac OS X comes with Python 2.7 out of the box.
You do not need to install or configure anything else to use Python 2. These instructions document the installation of Python 3.
The version of Python that ships with OS X is great for learning, but it’s not good for development. The version shipped with OS X may be out of date from the official current Python release, which is considered the stable production version.
Doing it Right¶
Let’s install a real version of Python.
Before installing Python, you’ll need to install GCC. GCC can be obtained by downloading Xcode, the smaller Command Line Tools (must have an Apple account) or the even smaller OSX-GCC-Installer package.
If you already have Xcode installed, do not install OSX-GCC-Installer. In combination, the software can cause issues that are difficult to diagnose.
If you perform a fresh install of Xcode, you will also need to add the commandline tools by running xcode-select —install on the terminal.
While OS X comes with a large number of Unix utilities, those familiar with Linux systems will notice one key component missing: a package manager. Homebrew fills this void.
To install Homebrew, open Terminal or your favorite OS X terminal emulator and run
The script will explain what changes it will make and prompt you before the installation begins. Once you’ve installed Homebrew, insert the Homebrew directory at the top of your PATH environment variable. You can do this by adding the following line at the bottom of your
If you have OS X 10.12 (Sierra) or older use this line instead
Now, we can install Python 3:
This will take a minute or two.
Homebrew installs pip pointing to the Homebrew’d Python 3 for you.
Working with Python 3¶
At this point, you have the system Python 2.7 available, potentially the Homebrew version of Python 2 installed, and the Homebrew version of Python 3 as well.
will launch the Homebrew-installed Python 3 interpreter.
will launch the Homebrew-installed Python 2 interpreter (if any).
will launch the Homebrew-installed Python 3 interpreter.
If the Homebrew version of Python 2 is installed then pip2 will point to Python 2. If the Homebrew version of Python 3 is installed then pip will point to Python 3.
The rest of the guide will assume that python references Python 3.
Pipenv & Virtual Environments¶
The next step is to install Pipenv, so you can install dependencies and manage virtual environments.
A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.
For example, you can work on a project which requires Django 1.10 while also maintaining a project which requires Django 1.8.
This page is a remixed version of another guide, which is available under the same license.
This opinionated guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis.
O’Reilly Book
This guide is now available in tangible book form!
All proceeds are being directly donated to the DjangoGirls organization.
Источник
dineshviswanath / python_web_dev_flask_environment_setup.md
#Starting Python Web development in Mac OS X#
Objective: Getting started with Python Development Operating System: Mac OS X Python version installed: 3.5 (5th December 2015)
Mac OS uses default 2.x version out of box. To check whether, python has been installed successfully. try the following command.
Above step ensure that Python 3.5 has been installed successfully.
This is the high level outline of this post: Mas OS X -> Python 3.5 -> Virtaulenv -> Flask —> app.py(first Hello world )
Installing virtaulenv: (Step 1 of Why use virtualenv?
- Having different version of libraries for different projects
- Solves the elevated privillege issue as virtualenv allows you to install with user permission
Now lets create the first flask app
Now we will create a virtualenv
If you list the contents of the hello_flask directory, you will see that it has created several sub-directories, including a bin folder (Scripts on Windows) that contains copies of both Python and pip. The next step is to activate your new virtualenv.
Installing Flask in your virtaulenv
Create a new file called app.py
Open the web browser with http://localhost:5000
This comment has been minimized.
Copy link Quote reply
automactic commented Jan 3, 2017
Should it be pip3 install Flask ?
This comment has been minimized.
Copy link Quote reply
itsgokhanyilmaz commented Jan 28, 2017
yes, it should be pip3 if you use python 3.x
This comment has been minimized.
Copy link Quote reply
LordA98 commented Mar 19, 2017
Thank you!
A couple of notes for other people:
- Create the app.py file within the ‘hello_flask’ folder. It should should be on the same level as bin and include. (That’s where I’ve got it anyway — and it works).
- In your terminal — provided you’ve got all the above steps done and your current terminal position looks similar to this : (hello_flask) Alexs-MacBook-Pro-3:hello_flask Lord$ , type python app.py . Then run the above localhost:5000 in your browser.
This comment has been minimized.
Copy link Quote reply
neozero25 commented Nov 5, 2017
when I type python app.py and press return it say:
File «app.py», line 3
app = Flask(name)
^
IndentationError: unexpected indent
but I just copy and paste that code from above
what is wrong with that?
This comment has been minimized.
Copy link Quote reply
gopaljaiswal commented Nov 10, 2017 •
@neozero25 I added a snapshot. It is working for me. Need to maintain line alignment.
This comment has been minimized.
Copy link Quote reply
tubala commented Jan 1, 2018
This comment has been minimized.
Copy link Quote reply
theblindguidedog commented Jan 25, 2019
Hi gopaljaiswal, why have you indented |return ‘Hello, Flask!’ (and) app.run(debug=True)| so much? As far as I know, this should produce an error.
This comment has been minimized.
Copy link Quote reply
horsecoin commented Apr 14, 2019 •
I had to:
python3 -m http.server
2019-04-13 15:29:45 ☆ nickademous in
/projects/hello_flask
± |master ↑1 ↓2 S:387 U:367 ?:444 ✗| → python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) .
then open site in new terminal and
2019-04-13 16:23:10 ☆ nickademous in
/projects/hello_flask
± |master ↑1 ↓2 S:387 U:367 ?:444 ✗| → python3 app.py
- Serving Flask app «app» (lazy loading)
- Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead. - Debug mode: on
- Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
- Restarting with stat
- Debugger is active!
- Debugger PIN: 176-388-923
127.0.0.1 — — [13/Apr/2019 16:23:52] «GET / HTTP/1.1» 200 —
127.0.0.1 — — [13/Apr/2019 16:23:52] «GET /favicon.ico HTTP/1.1» 404 —
it works with my edits of the app.py all the indents lol
#!/bin/bash python3
from flask import Flask
app = Flask(name)
@app.route(‘/’)
def index():
return ‘Hello, Flask. ‘
if name == ‘main‘:
app.run(debug=True)
Heres my full log:
2019-04-13 14:21:04 ☆ nickademous in
virtualenv notes from my mac!
sudo pip3 install virtualenv
—————
The directory ‘/Users/nick/Library/Caches/pip/http’ or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo’s -H flag.
The directory ‘/Users/nick/Library/Caches/pip’ or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo’s -H flag.
———
Installing collected packages: virtualenv
Successfully installed virtualenv-16.4.3
virtualenv —version
16.4.3
2019-04-13 14:28:19 ☆ nickademous in
± |master ↑1 ↓2 S:387 U:367 ?:443 ✗| → mkdir
2019-04-13 14:30:03 ☆ nickademous in
± |master ↑1 ↓2 S:387 U:367 ?:443 ✗| → cd
2019-04-13 14:30:20 ☆ nickademous in
/projects
± |master ↑1 ↓2 S:387 U:367 ?:443 ✗| → virtualenv hello_flask
Using base prefix ‘/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7’
New python executable in /Users/nick/projects/hello_flask/bin/python3.7
Also creating executable in /Users/nick/projects/hello_flask/bin/python
Installing setuptools, pip, wheel.
done.
Installing collected packages: click, MarkupSafe, Jinja2, itsdangerous, Werkzeug, flask
Successfully installed Jinja2-2.10.1 MarkupSafe-1.1.1 Werkzeug-0.15.2 click-7.0 flask-1.0.2 itsdangerous-1.1.0
Источник