Как запустить код в атоме python

от admin

Turning Atom Into a Lightweight Python IDE¶

Atom is the self-proclaimed “hackable text editor for the 21st Century.” It has a nice modern interface, and is highly customizable yet can also be used productively with minimal setup and configuration.

Requirements¶

Any IDE should ease your development experience by providing the following:

  • It should provide excellent, configurable syntax colorization.
  • It should allow for robust tab completion.
  • It should offer the ability to jump to the definition of symbols in other files.
  • It should perform automatic code linting to help avoid silly mistakes.
  • It should be able to interact with a Python interpreter such that when debugging, the editor will follow along with the debugger.

Atom does all this and more, but some functionality requires you to select and install packages.

Which Version?¶

The latest version is the best version. Atom is regularly maintained, so the latest version will have the latest bug fixes and updates.

Installation¶

On the main page, click the big red button to download the installer, then run the installer.

If it is not offering the correct platform: on the main page, below the big red button, click Other Platforms and find the installer for your operating system.

If you already have Atom installed, but want to check for a newer version, go to Help -> Check for Update .

Basic Settings¶

Atom can be used out of the box with no setup as a text editor. It automatically recognizes file types and helpfully highlights text accordingly. To use in this manner, write your Python files in Atom, then run them in your Python command prompt.

Extending the Editor¶

When you first open Atom, a Welcome Guide appears. This provides some quick and helpful information on how to open projects, install packages, and customize your themes and styling.

Atom has great documentation on how to hack and configure it. Read the Flight Manual for tons of information on everything you can do. You can also watch a Getting Started video.

Atom has a configuration file which you can modify called config.cson. Access it via File -> Config.

Here you can quickly change the theme or font size. Some packages will require you to add configs or make adjustments here. Read the documentation carefully when installing packages.

In general, you can extend Atom by installing packages, and then accessing their functionality from the Packages drop-down menu. Access the Install Packages page from the Welcome Guide page. If the Welcome Guide is not open, you can open it via Help -> Welcome Guide .

Keyboard shortcuts are specified in the packages menus if available.

The Useful Packages presented below are only a few options of many.

Useful Packages¶

Running Scripts¶

To run scripts within Atom, you will need to install the Script package. The Script package supports a ton of languages, including Python!

Autocompletion¶

By default, Atom knows which Python packages you have imported, variables you have created and so on. Autocomplete ships with Atom and requires no setup.

Code Linting¶

To get code linting functionality in Atom, you will need to install a linting package of which there are many to choose from. linter-pylint works well, and requires minimal setup.

White Space Management¶

Atom knows when you are writing Python and helps you out by dealing with spaces and tabs in the same way. When in a Python file, if you type 4 spaces, then hit delete, you are taken back a tab.

The Whitespace package ships with Atom and requires no setup. Under the Packages -> Whitespace menu, you will find tools to turn all tabs into spaces, all spaces into tabs, among other whitespace-related options.

Debugging¶

To use a Python debugger in Atom, you will need to install the python-debugger package. Once installed, turn on the debugger by going to Packages -> python-debugger -> Toggle .

© Copyright 2017, University of Washington, Natasha Aleksandrova, Christopher Barker, Brian Dorsey, Cris Ewing, Christy Heaton, Jon Jacky, Maria McKinley, Andy Miles, Rick Riehle, Joseph Schilz, Joseph Sheedy, Hosung Song. Creative Commons Attribution-ShareAlike 3.0 license

Настройка Atom от GitHub для работы с PHP, Python и некоторыми другими языками программирования

Изначально считаем что у Вас установлена поддерживаемая операционная система, Node.JS и Atom. В примерах мы работаем в OpenSUSE (13.1) в нём (и вообще в дистрибутивах *nix) уже «из коробки» обычно есть не только Python но PHP и другие языки программирования. Так же исправно работает на Ubuntu (>12.04). Если у Вас Windows 7 или 8, а раньше Вы с ними (языками) не работали то их предварительно необходимо скачать и установить.
Примечание: перед началом работы желательно запускать Atom под root.
опыт показывает — работает стабильнее

Linter

Идеология Atom к подсветке в том, что основным пакетом для работы с синтаксисом и его анализа будет Linter, который является верхним уровнем в API для других линтеров кода. Это сделано для прекращения «войны между плагинами» (The idea is to stop the linter plugins war, by providing a top level API for linters to parse and display errors in the Atom editor). Тем не менее, не все сторонние разработчики придерживаются этой идеологии и пишут свои плагины.

  • linter-php , для PHP `php -l`
  • linter-phpcs , для PHP, `phpc`
  • linter-phpmd , для PHP, `phpmd`
  • linter-pylint , для Python, `pylint`
  • linter-pyflakes , для python, `pyflakes`
  • linter-pep8, для python, `pep8`
  • linter-flake8, для python, `flake8`
  • linter-javac , для Java, `javac`
  • linter-jshint , для JavaScript and JSON, `jshint`
  • linter-jscs , для JavaScript, `jscs`
  • linter-scss-lint , для SASS/SCSS, `scss-lint`
  • linter-coffeelint , для CoffeeScript, `coffeelint`
  • linter-csslint , для CSS, `csslint`
  • linter-rubocop , для Ruby and Ruby on Rails, `rubocop`
  • linter-tslint , для Typescript, `tslint`
  • linter-xmllint , для XML, `xmllint`
  • linter-shellcheck , для Bash, `shellcheck`
  • linter-scalac , для Scala, `scalac`
  • linter-clang , для C / C++, `clang`
  • linter-ruby , для ruby, `ruby -wc`
  • linter-lua , для Lua, `luac -p`
Пакет Script: запуск программ из Atom

Script — пакет для запуска кода в atom.

Установка пакета Script, возможна из командной строки:

или меню
Packages->Settings View->Install->Packages

Каждый язык работает, при наличии предварительно установленного компилятора / интерпритатора.
Пакет Script обновляется довольно часто. Например поддержка Swift появилась менее двух недель назад. Так что скорее всего в ближайшее время появится поддержка новых языков.

Для запуска программы необходимо выбрать
Packages—>Script—>Run

Дополнительные опции можно найти в документации либо на страницах Atom`а или проекта.

Для функционирования должен быть создан рабочий каталог.
Путь к нему нужно прописать здесь:
Packages—>Script—>Configure Script—>Current Working Directory
Заявку разработчикам на поддержку нового языка можно оставить здесь (отвечают быстро)

И немного юмора от разработчиков пакета Script,
у которых, судя по всему, спрашивают всё на свете:

первод: Атом не может найти Нод | Руби | Питон | Мои носки

Python

Поддержка подсветки этого языка идёт изначально. Пакеты для работы с синтаксисом и отладки:
Linter + Language Python + Linter Python Pep8 + Script

Читать:
Defender game master g2 как настроить

Script запускает код на Python, а Linter и Linter Python Pep8 покажут синтаксические ошибки.
Возможно Вам, для работы с Python также поможет Atom Python Debugger.
Подсветка ошибок и запуск после установки будут выглядеть так:

Swift
  • пакет Swift Playground
  • и уже описанный пакет Script.

Терминал

Для запуска исполняемого кода С, C++, Java иногда проще использовать сторонний пакет (не пакет Atom, а пакет вашего дистрибутива), который запускается через терминал, поскольку сам Atom поддерживает большое количество языков. Если Atom выступает в качестве редактора кода, a терминал рядом запускает его — это очень удобно для нас, поскольку терминал не имеет такое преимущество редактирования, как Atom.
Для запуска терминала в окне Atom установите пакет Term. Для запуска терминала в окне Atom выбрать
Packages—>Command Palette—>Toggle и Term
с нужными параметрами.

В заключении ещё один интересный кликабельный анимационный gif от разработчиков script, ссылки.

atom-editor Getting started with atom-editor Running a «Hello, World!» program in Python using Atom from scratch

Atom is versatile and flexible text editor and has hundreds of community-made, open-source packages that can compile and run source files, for many languages. This guide will show how easy it is to code Python with the Atom editor.

This guide assumes you do not have Python nor Atom installed in your system.

Step 1: Installing Python

Python can be installed from the either the official website, or if you’re using Linux, through package managers (however Python usually comes pre-installed anyways).

If you’re a Windows user, do not forget to set python.exe to your %PATH% .

Step 2: Installing Atom

You can install the Atom editor from the official website or through package managers.

Step 3: Configuring Atom

For more information about installing packages, and themes, read this dedicated topic.

In order to compile and run programs, the Atom community provides packages to fill that need. For this example, we will be using script to run our program.

Go to File > Settings > Install.

Type script in the search bar and install it. When it is installed, it should be listed in "Packages" in the Settings bar. It should be noted that script is not capable of user input.

If you’re using MacOS or Linux, you can use the apm package manager to install packages.

Step 4: Programming and executing

Pick a directory where you would like to store your PY source file.

Make sure you can see the Tree View pane; if you cannot see this pane, you can toggle it by going to View > Toggle Tree View.

Go to File > Add Project Folder and select a directory which will be set as your root directory for a project.

Right-click the folder and click New File, then enter in hello-world.py and type in the following code:

Press CTRL + SHIFT + B to run the script. Alternatively, you can go to View > Toggle Command Palette and enter Script: Run .

Name already in use

BeginCoder / static / posts / how_to_set_up_the_Atom_for_python / how_to_set_up_the_Atom_for_python.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

atom icon

Почему Atom? Для меня выбор был прост. Если говорить о редакторах, то он просто проще, чем vim или emacs. Может быть когда-нибудь я осилю какой нибудь из этих редакторов, но, пока я ещё не научился достаточно хорошо программировать, хочется больше уделять времени именно программированию. Можно использовать PyCharm — он реально удобен и прост в освоении, но тут стоит учитывать, что в бесплатной версии нет множества крутых фишек, таких, как поддержка веб-фреймворков, работы с б.д., крутой поддержки js и т.д. А так как я программист начинающий, хочется использовать минимум денежных вложений. (Тут, конечно есть обходные пути: Студенческая лицензия(Для обучения), Лицензия для свободных продуктов(У меня продуктов пока вообще нет. Поэтому тоже отпадает), Использование ключей с трекеров и т.д.(Кому как совесть позволяет)). Поэтому Atom. Он легок в использовании, бесплатен, гибок и т.д. Нужно только его чуть настроить.

Вступление получилось больше чем хотел, поэтому перейдём сразу к делу.

Настройка atom, в общем, заключается просто в установке и настройке нужных пакетов. Процесс установки очень прост — заходим в настройки(В Linux и OS X «Edit»-«Preferences»-«Install», в WINDOWS — «File»-«Settings»-«Install». Можно просто использовать сочетание клавиш «Ctrl + ,», когда запомнишь получается быстрее.), вбиваем в строку поиска нужный пакет, находим его в результат и жмём «Install».

И так, плагины для Python:

screen of language-python

https://atom.io/packages/language-python Данный пакет стоит из коробки. И подсвечивает он всё как надо. Конечно пока нет подсветки async перед def и прочих новых фич из мира python, но и без это вполне жить можно.(Может конечно я чего-то не понимаю, а может подсветки async просто пока нет и будет потом. )

https://atom.io/packages/autocomplete-python Пакет справляется с подстановкой не только связанной с данным файлом, но также и с подстановкой объектов импортированных из других файлов. Так же может сразу подставлять имена аргументов функций. Всё довольно интуитивно и просто. Если Вы используете виртуальное окружение(Если ещё не используйте, начните — это очень удобно!) в настройках пакета нужно указать (Я, обычно все проекты организую по одинаковой схеме, так удобнее при создании новых проектов — не нужно менять настройки. Папку с виртуальным окружением я ложу в корень проекта и называю «env». Пакет autocomplite-python использует переменную $PYTHON для указания корня проекта.):

  • Python Executable Paths — путь к бинарнику python. В моем случае: «$PROJECT/env/bin/python3».
  • Extra Path For Packages — путь к импортируемым пакетам. Тут тоже всё просто — указываем site-packages виртуального окружения и папку проекта(на тот случай если папка проекта у нас будет добавляться в PYTHONPATH, например как при использовании Django, чтобы импортировать от корня проекта). В моём случае: «$PROJECT/env/lib/python3.5/site-packages;$PROJECT».

В общем-то всё. По мимо этих настроек пакет содержит множество других, о которых можно прочитать на странице пакета.

Поиск ошибок и анализ качества кода

screen of message in linter-pylint

https://github.com/AtomLinter/linter-pylint Данный пакет использует пакет python — pylint, для проверки Вашего кода. Pylint — очень мощный пакет для анализа Ваше кода. Подробнее о нём можно прочитать здесь: https://www.pylint.org. Несмотря на то, что я использую виртуальные окружения, pylint я всегда устанавливаю глобально. Если устанавливаете pylint в виртуальное оркужени, нужно будет указать в настройках(linter-pylint использует переменную %p в качестве пути к корню проекта):

  • Executable — путь к файлу pylint. Например, он может быть таким: «%p/env/bin/pylint».

Также в настройках нужно указать путь к импортируемым модулям.

  • Python path — путь к импортируемым модулям. В моём случае: «%p/env/lib/python3.5/site-packages».

Также linter-pylint использует пакеты atom: lint и linter, поэтому они тоже должны быть установлены.

Related Posts