Sublime text как настроить под python

Настройка Python на Sublime text3

Все установочные сделала, компилятор прописала:

Теперь проблема с Tools->SublimeREPL->Python->Python пишет не удается найти файл, через CTRL + B тоже пишет:

[WinError 2] Не удается найти указанный файл

Что делать? Как РЕПЛ настроить?

1 ответ 1

Открываем Sublime Text -> Tools -> Build System -> New Build System

Вставляем в открывшийся файл следующие строки, чтобы получилось вот так:

Сохраняем файл с названием python3.sublime-build и не меняем путь предложенный редактором

Идем и ставим галочку Tools -> Build system -> python3

Если вам не требуется передавать через консоль в программу аргументы (например input()), то вы уже можете проверить работу создав и сохранив (без сохранения будет ошибка) тестовый файл, а затем нажав Ctrl+B. Снизу появится консоль с выводом результата.

Для проверки предлагаю выполнить следующий код:

——Делаем интерактивную консоль——

Заходим на сайт https://packagecontrol.io/installation и копируем содержимое бокса Sublime Text 3 в буфер обмена.

Открываем Sublime Text -> View -> Show Console и вставляем содержимое буфера обмена, затем жмем Enter. Если у вас ничего не произошло, то выполните ручную установку описанную на сайте из пункта 5.

Жмем Ctrl+Shift+P -> пишем Install Package -> пишем sublimeREPL и устанавливаем.

Поскольку в sublimeREPL установлен python 2, то идем в Sublime Text -> Preferences -> Browse Packages

Открываем в текстовом редакторе файл SublimeREPL -> config -> Python -> Main.sublime-menu

Находим внутри этого файла столбик с аргументами children -> args -> cmd и меняем значение «python» на «python3». Сохраняем и закрываем файл.

Открываем тестовый python-файл (например из пункта 4)

Открываем консоль редактора как в пункте 6 и пишем sublime.log_commands(True)

Sublime Text -> Tools -> sublimeREPL -> Python -> Python RUN current file и затем копируем из консоли строку repl_open целиком со всеми аргументами.

В консоли пишем sublime.log_commands(False)

Sublime Text -> Preferences -> Key Bindings. Забиндим хоткей для быстрого исполнения файла в интерактивной консоли REPL

Вставьте в User-конфиг (он пустой) следующий код (ключ keys сделайте свой по желанию, в «сommand» пишите «repl_open», а в «args» закидываете все атрибуты которые скопировали из консоли. Их не обязательно так разбивать по строкам, можно все в одну оставить:

  1. Сохраняем файл, перезапускаем Sublime Text и используем заданный хоткей.

Источник

Настройка Sublime Text для Python

Python

Программисты любят спорить о том, у кого «лучшая» среда разработки — какие инструменты лучше? Должен ли я использовать текстовый редактор или полноценную среду IDE? Какие плагины и пакеты следует использовать? Это все правильные вопросы, но суть в том, что: после того, как вы выбрали предпочтительный текстовый редактор/IDE, вы должны потратить значительное количество времени на его настройку и понять, как извлечь максимальную пользу из этого, так как это сэкономит вам время в будущем.

Мой выбор текстового редактора — Sublime Text 3. В этой статье я дам вам пятиэтапное руководство по настройке Sublime Text 3 для разработки с помощью Python.

1. Установка

Вы можете скачать и установить Sublime Text 3 здесь.

После установки первое, что вы захотите сделать, это установить диспетчер пакетов. Менеджер пакетов позволяет добавлять и удалять сторонние плагины, которые улучшат вашу среду разработки.

Откройте консоль Sublime с помощью CTRL + `. Затем скопируйте и вставьте код отсюда в консоль и нажмите enter. Установка пакета займет несколько секунд. После этого вы можете открыть командную панель с помощью CTRL + SHIFT + P и ввести имя пакета. Список параметров должен выглядеть следующим образом:

Если вы видите параметры управления пакетами, то вы знаете, что все правильно установили!

2. Рекомендуемые Sublime Text 3 плагины

Одна из лучших вещей в Sublime Text заключается в том, что разработчики могут использовать сторонние плагины для улучшения своей среды разработки. Нажмите «CTRL + SHIFT + P» и выберите «Package Control: Install Package». Затем вы cможете найти плагины, которые я рекомендую вам использовать для разработки в Python:

Anaconda

Anaconda — чрезвычайно мощный пакет Python для Sublime. Он предлагает:

  • Автодополнение кода Python
  • Python linting (подчеркивает как синтаксические ошибки, так и нарушения PEP8)
  • Документация Python
  • McCabe — проверка сложности
  • и много чего еще

Djaneiro

Djaneiro предлагает подсветку синтаксиса для HTML-шаблонов Django и автоматическое заполнение табуляцией для синтаксиса языка Django, например <% block%><% endblock%>.

После того, как вы установили Djaneiro, откройте HTML-файл, а в правом нижнем углу выберите язык, который используется в данный момент, затем выберите Djaneiro -> HTML (Django), чтобы обеспечить выделение синтаксиса Jango Template:

Автодополнение означает, что вам не нужно записывать фрагменты кода снова и снова. Например:

  • var + TAB генерирует <<>>.
  • block + TAB генерирует <% block%>
  • url + TAB генерирует
  • static + TAB генерирует

Полный список автодополнений в Djaneiro доступен здесь.

Самое главное, SideBar Enhancements отправляет файлы в свою корзину, если вы удаляете файл из Sublime Text (вместо того, чтобы быть полностью удаленным). Он также предлагает множество других функций, включая возможность создания новых файлов с боковой панели.

Requirements Txt

Это простой плагин, который предлагает подсветку синтаксиса для файлов requirements.txt. Используй это.

All AutoComplete

All AutoComplete расширяет автодополнение по умолчанию.

GitGutter

GitGutter помещает поле в Sublime Text, которое указывает, была ли строка добавлена, удалена или отредактирована. Это полезно для отслеживания внесенных изменений в предыдущие коммиты.

Другие (JavaScript/CSS) пакеты

Есть куча пакетов JavaScript/CSS, которые я также использую для моей разработки в Python Sublime Text 3. Я не буду подробно останавливаться на них, но вы все равно должны их посмотреть:

  • AngularJS — предлагает подсветку синтаксиса AngularJS и автодополнение.
  • jQuery — предлагает подсветку синтаксиса jQuery.
  • Trimmer — пакет для удаления конечных пробелов
  • CSS3 — подсветка синтаксиса CSS3 и автодополнение
  • Sass — подсветка синтаксиса Sass и автодополнение
  • Color Highlighter — показывает шестнадцатеричные, RGB и буквенные обозначения цвета для соответствующего цвета. Например, синий цвет в таблице стилей CSS будет выделен синим цветом, так что вы получите визуальное представление о цвете.

3. Макет

Большинство вариантов компоновки доступны в меню view.

В Views -> Columns вы можете переключить представление, чтобы отобразить 1, 2, 3 или 4 столбца, 1 или 2 строки или сетку 2 * 2. Мое предпочтение состоит в том, чтобы использовать раскладку из двух столбцов.

Другие настройки макета, которые вы, возможно, захотите рассмотреть:

  • используйте CTRL + KB для переключения боковой панели (я предпочитаю держать ее открытой всегда)
  • нажмите F11 для переключения полноэкранного режима
  • перейдите в меню View -> Ruler, чтобы выбрать отображаемый правый край. Я кодирую в соответствии со стандартами PEP8, поэтому установил правую границу в 80 символов.
  • перейдите в View -> Hide Minimap, чтобы скрыть мини-карту! Я нахожу ее раздражающей.

4. Горячие клавиши

Очень полезно потратить немного времени на изучение быстрых клавиш Sublime Text. Комбинации, которые я использую наиболее часто, перечислены ниже:

  • CTRL + K: удаляет текущую строку.
  • CTRL + X: разрезает текущую строку.
  • CTRL + SHIFT + UP перемещает выделенный текст вверх.
  • CTRL + SHIFT + DOWN перемещает выделенный текст вниз.
  • CTRL + W: закрывает текущую вкладку.
  • CTRL + KK: удаляет все от курсора до конца строки.
  • CTRL + F: найти.
  • CTRL + H: найти и заменить.
  • CTRL + KU: преобразование выбранного текста в верхний регистр.
  • CTRL + KL: преобразование выбранного текста в нижний регистр.
  • CTRL + KB: переключить боковую панель.
  • CTRL + [: отменить текущую строку.
  • CTRL +]: отступ текущей строки.
  • CTRL + M: перейти к закрывающей скобке или нажмите еще раз, чтобы перейти к открывающей скобке.
  • CTRL + /: комментарий/раскомментирование текущей строки или выбора.
  • ALT +.: Завершает текущий тег HTML.
  • ALT + SHIFT + W: обернуть тег (по умолчанию —

Некоторые специфичные горячие клавиши:

  • ALT + SHIFT + [NUMBER]: разбивает представление на столбцы [NUMBER], где [NUMBER] — 1-4.
  • ALT + SHIFT + 8: разбивает представление на сетку 2×2.
  • CTRL + 0: фокусируется на боковой панели.
  • CTRL + 1-4: фокусируется на столбце 1-4.
  • CTRL + SHIFT + 1-4: перемещает файл в столбец 1-4.

Полный список сочетаний клавиш Sublime Text 3 доступен здесь.

5. Консоль

Когда я впервые начал программировать на Python, я использовал Enthought Canopy. По умолчанию это отличная встроенная консоль IPython. Настройка консоли ST3 немного сложнее, но это того стоит.

Следуя этому видео на YouTube, откройте командную панель, используя CTRL + SHIFT + P и выберите install package. Установите пакет SublimeREPL. Затем перейдите в Preferences -> Browse Packages -> SublimeREPL -> Config -> Python. Откройте файл Main.sublime-menu. Найдите «id»: «repl_python_run» с помощью CTRL + F и добавьте параметр «-i» в раздел «cmd» под «args».

Затем перейдите в Tools -> Build System -> New Build System и введите код из этого ответа на StackOverflow:

Источник

Setting Up Sublime Text 3 for Full Stack Python Development

Table of Contents

Sublime Text 3 (ST3) is a lightweight, cross-platform code editor known for its speed, ease of use, and strong community support. It’s an incredible editor right out of the box, but the real power comes from the ability to enhance its functionality using Package Control and creating custom settings.

In this article, we’ll look at how to setup Sublime Text for full stack Python development (from front to back), enhance the basic functionality with custom themes and packages, and use many of the commands, features, and keyword shortcuts that make ST3 so powerful.

Note: This tutorial assumes you’re using a Mac and are comfortable with the terminal. If you’re using Windows or Linux, many of the commands will vary, but you should be able to use Google to find the answers quickly given the info in this tutorial.

Before we start, let’s address what I mean exactly by “full stack.”

In today’s world of HTML5 and mobile development, JavaScript is literally everywhere. EVERYWHERE. Python coupled with a framework such as Django or Flask is not enough. To really develop a website from end-to-end, you must be familiar with JavaScript (and the various JavaScript frameworks), REST APIs, responsive design, and of course HTML and CSS, and so on.

Let’s face it: as a programmer, you are like any other craftsman. If you want to be the best you can be, then you need your tools to be sharp. Your development environment must be set up for full stack development—which is exactly what we are going to do right now.

Free Bonus: 5 Sublime Text Tweaks to Boost Your Python Productivity, a free course that shows you how to optimize your Python development setup.

Features

Let’s start by looking at a few of the default features of Sublime Text 3:

Split Layouts allow you to arrange your files in various split screens. This is useful when you are doing test driven development (Python code on one screen, test scripts on another) or working on the front end (HTML on one screen, CSS and/or JavaScript on another).

Vintage Mode provides you with vi commands for use within ST3.

  • Chrome-like Tabs make navigating and editing several files much simpler.
  • Automatic loading of the last session re-opens all files and folders you had open when you closed the editor the last time. I leave ST3 open all the time, with various projects open, so if I reset the computer, it opens the files and folders right back up.
  • Code Snippets increase your productivity by giving you the ability to create common pieces of code with a single keyword. There are a number of default snippets. To try one for yourself, open a new file, type in lorem , and press Tab . You should get a paragraph of lorem ipsum text. Also, if you type defs and then press Tab in a Python file, it will setup a generic function.
  • Note: You can also create your own snippets: Tools > New Snippet. Refer to the documentation for help, and also check out some of my snippets here.

    Customizing Sublime Text 3

    After you download ST3, you can customize it.

    Install the subl command line tool

    Just Like TextMate has the mate command, Sublime Text has a command line tool called subl that allows you to open one file, or an entire directory of files and folders, from the terminal.

    To enable this command, create a symbolic link to the subl binary:

    Ensure that the link works by opening Sublime:

    If that didn’t work, you probably need to add /bin to your path:

    Then repeat step one.

    Note: If you are still having trouble, check out this article for help. You can also read up on creating the symbolic links in Windows and Linux.

    Now you can open a file or directory using the following commands:

    If there are spaces in the path, you must surround the entire path in double quotes:

    To view all the commands, open up the help file:

    Install Package Control

    To begin taking advantage of the various packages for extending Sublime’s functionality, you need to manually install the package manager called Package Control. Once you have it installed, you can use it to install, remove, and upgrade all other ST3 packages.

    1. To install, copy the Python code for Sublime Text 3 found here. Click View > Show Console to open the ST3 console. Paste the code into the console. Press Enter . Reboot ST3.
    2. You can now install packages by using the keyboard shortcut Cmd + Shift + P . Start typing install until Package Control: Install Package appears. Press Enter and search for available packages.

    Here are some other relevant commands:

    • List Packages shows all your installed packages.
    • Remove Package removes a specific package.
    • Upgrade Package upgrades a specific package.
    • Upgrade/Overwrite All Packages upgrades all your installed packages.

    Check out the official documentation to view more commands.

    Create a Custom Settings File

    You can fully configure Sublime Text using JSON-based settings files, so it’s easy to transfer or synchronize your customized settings to another system. First, we need to create our customized settings. It’s best to create a base file for all environments as well as language-specific settings files.

    To set up a base file, click Sublime Text > Preferences > Settings — User. Add an empty JSON object to the file and add your settings like so:

    1. For language specific settings, click Sublime Text > Preferences > Settings — More > Syntax Specific — User. Then save the file using the following format: LANGUAGE.sublime-settings. For Python-specific settings, save the file as Python.sublime-settings.
    2. You can obviously configure your settings to your liking. However, I highly recommend starting with my base and Python-specific settings and then making changes as you see fit.
    3. Optional: You can use Dropbox to sync all your settings. Simply upload your settings files to Dropbox and load them from there to sync the Sublime environments on all your machines.
    4. A good reference for settings can be found at the Sublime Text Unofficial Documentation.

    Themes

    ST3 also gives you the option to change the overall theme to better suit your personality. Design your own. Or, if you’re not artistically inclined, you can download one of the various custom themes designed by the Sublime community through Package Control. Check out ColorSublime to preview themes before installing them.

    The ever popular Soda Dark Theme and the minimal Flatland are two of my personal favorites.

    After installing a theme, make sure to update your base settings through Sublime Text > Preferences > Settings — User:

    Packages

    Besides the packaged themes, I take advantage of the following packages to speed up my workflow.

    SideBarEnhancements

    SideBarEnhancements extends the number of menu options in the sidebar, speeding up your overall workflow. Options such as New File and Duplicate are essential and should be part of ST3 out of the box. The Delete option alone makes it worth downloading. This feature simply sends files to the Trash, which may seem trivial, but if you delete a file without it, then it’s very difficult to recover unless you’re using a version control system.

    Download this now!

    Anaconda

    Anaconda is the ultimate Python package. It adds a number of IDE-like features to ST3 including the following:

    • Autocompletion works by default, but there are a number of configuration options.
    • Code linting uses either PyLint or PyFlakes with PEP 8. I personally use a different linting package, as I will explain shortly, so I disable linting altogether within the user-defined Anaconda settings file, Anaconda.sublime-settings, via the file menu: Sublime > Preferences > Package Settings > Anaconda > Settings — User:
    • McCabe code complexity checker runs the McCabe complexity checker tool within a specific file. If you’re not familiar with what complexity is, be sure to visit the link above.
    • Goto Definitions finds and displays the definition of any variable, function, or class throughout your entire project.
    • Find Usage quickly searches where a variable, function, or class has been used in a specific file.
    • Show Documentation shows the docstring for functions or classes (if defined, of course).

    You can view all of the features here or within the README file in ST3’s Package Settings: Sublime Text > Preferences > Package Settings > Anaconda > README.

    Note: SublimeCodeIntel is another popular package that has many of the same features as Anaconda. I suggest testing them both out.

    Djaneiro

    Djaneiro supports Django templating and keyword highlighting and provides useful code snippets (tab completions) for Sublime Text. The snippet system is an incredible time-saver. You can create common Django blocks with only a few keystrokes for templates, models, forms, and views. Check out the official documentation to see a list of snippets.

    My personal favorites are for templating: var creates << >> and tag creates <% %>.

    requirementstxt

    requirementstxt provides autocompletion and syntax highlighting as well as a nice version management system for your requirements.txt files.

    SublimeLinter

    SublimeLinter is a framework for ST3 linters. The package itself does not include any actual linters; those must be installed separately via Package Control using the SublimeLinter-[linter_name] naming syntax. You can view official linters here. There are also a number of third party linters, which can be viewed in Package Control. Check out the installation instructions here.

    Note: Most of these linters have dependencies associated with them, so please read the installation instructions before installing.

    You can customize each linter in the user-defined SublimeLinter.sublime-settings file: Sublime Text > Preferences > Package Settings > SublimeLinter > Settings — User. For example, I ignore the following PEP 8 errors and warnings:

    GitGutter

    GitGutter shows little icons in ST3’s gutter area that indicate whether a line has been inserted, modified, or deleted since the last commit.

    Note: If you want support for a number of distributed version control systems (Git, SVN, Bazaar, and Mercurial), check out Modific.

    FTPSync

    FTPSync syncs your project with your remote files. Simply open the file to download it (if the remote file is newer than your local file) and upload it to your remote server with every save. That’s a great way to keep your local and remote(s) in sync. You’ll want to make sure to add at least one remote connection by clicking Sublime Text > Preferences > Package Settings > FTPSync > Setup FTPSync.

    I personally set the password to null because I don’t want it visible in that file. FTPSync just asks for my password after each save.

    AdvancedNewFile

    AdvancedNewFile is used to create a new folder or file from within ST3 with key bindings alone.

    Simply bring up the AdvancedNewFile input through the appropriate key binding. Then, enter the path, along with the file name into the input field. Upon pressing Enter , the file will be created. In addition, if the directories specified do not yet exist, they will be created. By default, the path to the file being created will be filled shown in the status bar as you enter the path information.

    For a more detailed explanation on its usage, check out the documentation on GitHub. Be sure to read about Tab Completion as well as Predefined Aliases.

    I replaced the normal Cmd + N command to create a new file with AdvancedNewFile by adding the following code to the Key Bindings — User file: Sublime Text > Preferences > Package Settings > AdvancedNewFile > Key Bindings — User:

    You can also setup a default directory to start with: Sublime Text > Preferences > Package Settings > AdvancedNewFile > Settings — User

    Now when I create a new file, the /Users/michaelherman/Documents/repos string is automatically inserted first, since 99% of the time I store all my scripts in that directory.

    Emmet

    Emmet, previously known as Zen Coding, uses simple abbreviations to generate HTML or CSS code snippets.

    For example, if you type a bang, ! , and press Tab in an HTML file, then the HTML5 doctype and a few basic tags will be generated:

    Check out the official documentation as well as this handy cheat sheet for more info.

    Markdown Preview

    Markdown Preview is used for previewing and building markdown files.

    To use, open the Package Manager and type Markdown Preview to show the available commands:

    • Markdown Preview: Python Markdown: Preview in Browser
    • Markdown Preview: Python Markdown: Export HTML in Sublime Text
    • Markdown Preview: Python Markdown: Copy to Clipboard
    • Markdown Preview: GitHub Flavored Markdown: Preview in Browser
    • Markdown Preview: GitHub Flavored Markdown: Export HTML in Sublime Text
    • Markdown Preview: GitHub Flavored Markdown: Copy to Clipboard
    • Markdown Preview: Open Markdown Cheat Sheet

    Once converted, the output file will be updated on each subsequent save.

    Keyboard Shortcuts

    • Goto Anything Cmd + P is used for quickly finding and opening files. Just type in a part of a path and filename within a project and you can easily open that file. This is great for quickly opening files in large Django projects.
    • Goto Line Number Ctrl + G takes you to a specific line number in an active file.
    • Goto Symbol Cmd + R lists all functions and classes within a file to make them easier to find. Simply start typing the one you want.
    • Go to beginning of line Cmd + Left and Go to end of line Cmd + Right help you navigate within lines.
    • Delete current line Ctrl + Shift + K deletes the current line.
    • Multi-Edit is by far my favorite shortcut:
      • Select a word and press Cmd + D to select the next same word. Then press Cmd + D again to select the next same word again, and so on.
      • Press Cmd + Left Button to create a cursor for editing everywhere you click.
    • Block select Option + Left Button is used to select a block of text. It’s perfect for removing blank space when formatting a CSV file.

    Note: For more shortcuts, take a look at this article.

    Custom Commands

    It’s easy to write your own custom commands and key bindings with Python. I currently use this workflow:

    1. Copy the path of the current file to the clipboard (link).
    2. Close all tabs except the active one (link).

    Install these by adding the Python files to your /Sublime Text 3/Packages/User directory via the file menu (Sublime > Preferences > Browse Packages) and then opening the User directory. To complete the setup, bind them from the Key Bindings — User file (Sublime Text > Preferences > Package Settings > AdvancedNewFile > Key Bindings — User).

    Additional Resources

    Free Bonus: 5 Sublime Text Tweaks to Boost Your Python Productivity, a free email class that shows you how to optimize your Python + Sublime development setup for maximum efficiency.

    Conclusion

    I hope that this article was helpful to you and that you were able to integrate some of the above packages and custom settings along with your own based on your personal preferences to improve your workflow.

    If you have any questions or suggestions of your own, please let me know in the comments below. Finally, check out the dotfiles folder in this repo to view all the resources that I created. Cheers!

    Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

    Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

    Master Real-World Python Skills With Unlimited Access to Real Python

    Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

    Master Real-World Python Skills
    With Unlimited Access to Real Python

    Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

    What Do You Think?

    Real Python Comment Policy: The most useful comments are those written with the goal of learning from or helping out other readers—after reading the whole article and all the earlier comments. Complaints and insults generally won’t make the cut here.

    What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

    Источник

    Читайте также:  Нас ничего не сломается
    Оцените статью