Sublime text как запустить код
Перейти к содержимому

Sublime text как запустить код

  • автор:

Запустить код Python в Sublime Text 3

Запустить код Python в Sublime Text 3

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

В этом руководстве будет рассказано, как запустить код Python в возвышенном тексте 3.

Мы можем запускать код Python внутри Sublime Text с использованием этих встроенных систем сборки. Нажав Ctrl + B , Sublime 3 запустит код python внутри интегрированной консоли (при условии, что мы сохранили файл с расширением .py).

Но проблема с этой реализацией заключается в том, что с помощью этого метода мы не можем выполнять интерактивные действия, такие как выполнение функций пользовательского ввода с помощью input() или любое другое взаимодействие с программой.

Для этого нажимаем Ctrl + Shift + P в Windows и набираем Install Package Control . Пользователи macOS могут использовать Cmd + Shift + P для того же.

Затем нам нужно установить Terminus через Package Control. Поэтому мы снова нажимаем те же клавиши и набираем Package Control: Install Package , а затем набираем Terminus .

Затем мы переходим в меню Инструменты и выбираем опцию Сборка системы . Здесь мы выбираем New Build System и вставляем код ниже.

Запуск программ Python на Sublime Text 3

Привет разработчикам Python, здесь мы узнаем, как запускать программы python в редакторе Sublime Text 3, загружать и устанавливать Sublime Text 3, устанавливать пакеты и многое другое.

Существуют различные IDE и текстовые редакторы для запуска кода python. Если вы новичок, то это нормально использовать текстовый редактор, но если вы разработчик, то, без сомнения, вы будете знакомы с важностью IDE. И вы также можете обратиться к этой ссылке Best Python IDEs для подробного объяснения Python IDEs . Хотя Sublime Text 3 — это текстовый редактор, но он имеет некоторые IDE-подобные функции, такие как проекты и “сборки” для выполнения других программ изнутри редактора.

Редактор Sublime Text 3

Преимущества

  • Это легкий редактор для разработчиков.
  • Он наиболее популярен среди разработчиков.
  • Самое лучшее в Sublime Text 3 то, что он не требует много места для установки и работать с ним очень удобно и комфортно.
  • Sublime Text 3.0 был выпущен 13 сентября 2017 года.
  • Он изначально поддерживает множество языков программирования, а также языки разметки.

Особенности Sublime Text 3

  • Кросс-платформенный
  • Sublime Text 3 может работать на Windows, Linux и Mac.
  • Вам нужна только одна лицензия для использования Sublime Text 3 на каждом компьютере, на котором вы хотите использовать Sublime Text 3, независимо от того, какую ОС они используют.
  • Мощная экосистема API и пакетов
  • Sublime Text 3 предоставляет множество мощных API Python, которые позволяют плагину выполнять множество встроенных функций.
  • Sublime Text раскрывает свои внутренние компоненты через интерфейс прикладного программирования (API), с которым программисты могут взаимодействовать с помощью языка программирования Python.
  • Встроенный интерпретатор Python включен в редактор. Встроенный интерпретатор полезен для проверки настроек редактора и быстрого тестирования вызовов API при разработке плагинов.

Палитра команд

Это еще одна мощная особенность Sublime Text 3. Он позволяет выполнять различные функции, такие как сортировка, изменение синтаксиса, а также изменение параметров идентификации.

Используя палитру команд, вы можете получить доступ ко многим вещам, таким как обработка проектов sublime, изменение синтаксиса файлов, вызов команд пакета и т. д. Чтобы использовать палитру команд – нажмите ctrl+shift+p, затем выберите команду и нажмите Enter.

Множественный выбор

Это одна из лучших особенностей Sublime Text 3. Используя эту функцию, вы сможете изменять несколько строк одновременно, а также быстрее манипулировать файлами. Он работает как быстрая замена для поиска и замены или для применения одной и той же последовательности изменений к нескольким строкам одновременно.

Чтобы использовать множественное выделение, выделите блок текста, затем нажмите Ctrl+Shift+L, чтобы разделить его на одно выделение в строке, а затем нажмите Ctrl+D, чтобы выбрать следующее вхождение выбранного слова.

Другие Особенности

Помимо вышеперечисленных функций Sublime Text 3 имеет также некоторые другие функции, такие как:

  • Функция проверки орфографии
  • Автоматическое сохранение
  • Настраиваемые привязки клавиш
  • Макросы
  • Разделение редактирования
  • Расширенные настройки

Sublime Run Python Tutorial – Запустите свою первую программу

Без сомнения, Sublime text является самым любимым текстовым редактором в сообществе разработчиков и может служить отличным текстовым редактором Python. Итак, теперь мы увидим, как использовать его для python.

Загрузка и установка

Прежде всего, вы должны скачать его. Ссылка для скачивания-https://www.sublimetext.com/3 Вы увидите описание версии следующим образом:

Запуск программ Python на Sublime Text 3

И теперь вы должны выбрать один из них в качестве требования к вашему компьютеру. Установите скачанный файл.

Протестируйте простую программу

Теперь мы увидим выполнение программы python на SublimeText 3. Для этого мы должны сделать вот что:

  • Прежде всего откройте свой редактор sublime.
  • Создайте новый файл, выполнив следующие действия File->NewFile или нажав ctrl+N .
  • Затем сохраните этот файл как yourfilename.py . Расширение должно быть .py .
  • Затем напишите свой код.

Здесь берем простую программу, то есть сложение двух чисел. Так что код есть:

num1 = 7
num2 = 9
# Сложите два числа
sum = float(num1) + float(num2)
# Отображение суммы
print(‘Сумма <0>и <1>равна <2>’.format(num1, num2, sum))

Запуск Кода

Перейдите в пункт Инструмент в строке меню, а затем нажмите кнопку Построить систему и внутри нее выберите пункт Python. Затем перейдите в раздел Tool option и нажмите кнопку Build option, которая выполнит ваш код.

Запуск программ Python на Sublime Text 3

Итак, теперь, запустив приведенный выше код, мы получим следующий вывод:

Поздравляем, код python успешно работает на sublime! Надеемся, что эта статья будет полезна для вас. И если у вас есть какие-либо вопросы по поводу SublimeText 3, оставляйте свои комментарии!

Use Sublime!

Switching to Sublime has been the single biggest productivity booster in years. First, take a look at how beautiful it is:

ST3 in Win10 - Stata and Python

What is it?

Sublime Text is a free, cross-platform source code editor. You can easily add multiple plugins to extend its functionality, making it possible to edit and compile Stata code, Python scripts, R, LaTeX, Julia… the list is endless. You can also customize several other aspects like multiple-column layout or keyboard shortcuts, just to name a couple of examples.

You may be wondering what’s so special about running a Python script and compiling a LaTeX document from the same editor, since you may already use a Python IDE like PyCharms and a perfectly fine LaTeX editor like Texmaker. Thing is, large projects are usually complex and require handling a wide variety of files, so having one lightweight, customizable editor that can handle all of them makes it easier to both stay on top of the big picture and quickly dive into any kind of code for additional work.

Initial set up

Head over to sublimetext.com, download and install Sublime Text 3 (ST3) for your operating system.

After installing ST3 it is essential that you also install Package Control, which lets you easily add and remove additional plugins. Just follow these instructions to install it.

Customization

ST3 is a bit bare bones when first installed. However, it is extremely customizable. Below I share all my custom options, which have been thoroughly tested in MacOS, Linux and Windows.

Theme

The whole look of ST3 can be customized by installing themes. I know this is a matter of personal taste, but after trying many (many) themes, my current personal favorite is Monokai Pro. It is dark (of course), minimal and looks great in Windows and MacOS. To install it just invoke the command palette ( Tools ‣ Command Palette ), type install and hit Return . Then search for Monokai Pro and hit Return again to install it.

Monokai Pro theme and color scheme

Monokai Pro also has a bunch of “color filters” which let you change the overall feel of the theme. You can play around with them by going to Tools ‣ Command Palette ‣ Monokai Pro: select theme .

Sidebar

Although it isn’t visible at first, ST3 comes with a handy sidebar in which you can drop your project folders for easy access, besides listing all your open files. To activate it just go to View ‣ Side Bar ‣ Show Side Bar , and you will see something like the screenshot below:

ST3 sidebar

I also recommend that you install SideBarEnhancements, a plugin that adds a ton of useful functions for manipulating files and folders in the sidebar (you cannot even Move to trash without it!). To install it just invoke the command palette ( Tools ‣ Command Palette ), type install and hit Return . Then search for SideBarEnhancements and hit Return again to install it.

Development environment

Using Package Control we can easily add plugins that will let us use ST3 to edit and compile the following programs:

32 or 64 bits?

Before you continue, it is important to be sure whether you have a 32 or 64 bit operating system. The answer will determine which version of software you should install: if you have 32 bits, then you must choose 32 bit versions. If you have a 64 bits OS, then you can choose either… but it usually makes more sense to go for 64 bits software as well.

In Windows you can find out your system type by right-clicking on “This PC” (or “My Computer”, in older Windows) and selecting “Properties”. Look for “System type”, like in the screenshot below:

Windows 10 - System properties

On macOS (macOS?), select “About This Mac” from the Apple menu ( ) and you should see a pane like the one below:

About this Mac

Getting R to work with ST3 is pretty easy. If you haven’t already, go to the R-project and install the appropriate version for your OS. Once you’ve done that, you need to add R to you environment path. First locate your installation folder, which in Windows is something like

Inside you should see a folder for every version of R you have in your system. Go into the latest one and locate the bin\x64 or bin\x32 folder, depending on which version of R you installed. For example, the full directory in my Windows system is

To add this path, right-click on My Computer and choose Properties > Advanced (System Settings) > Environment Variables. Edit the Path variable (User or System, your choice) and add a line with the path you just located above. Accept these changes and then fire up the command line, where you should be able to execute R now:

Now you can run R scripts directly from within Sublime. To test it, create a new file with .R extension and write some R code, for example,

In order to run this simple script with R you need to choose your build system: go to Tools > Build System and choose R. Now you can select Tools > Build (or just hit Ctrl+B) to run this code! You should see the output on the Console pane of ST, on the bottom of your screen.

Python

Setting up a Python developing environment in ST3 is very easy, and the process is similar to R. First you’ll need to install Python in your machine. For data science, I recommend getting the Anaconda Python distribution.

Python 2.7 or 3.X?

Whether to use Python 2 or 3 is still a hotly debated topic, as a Google search will reveal. My recommendation is to take it easy, because (a) their syntax is fairly similar, (b) you can later switch and (c) the “typical” data science packages work for both versions. So I’d choose whatever version the book you’re using or the colleague you’re working with is using. If you have no reason to choose one or the other, then I’d probably go with Python 3, because that is the future, after all.

Install Python

Download and install the appropriate version of Anaconda Python (the process is fairly straightforward). Once you’re done, check that it is properly installed by firing up the Command prompt (Windows) or the Terminal (macOS) and just write down python . You should see the Python version and the Python shell ready:

Cool! Now you can use it as a fancy calculator:

Just type quit() to exit the Python shell.

Run a Python script in ST

Sublime supports Python without any further configuration, so you can just create a new file ending with .py extension and write some Python code:

You should be seeing the code with syntax highlighting, similar to the above code block. If you don’t, make sure you see “Python” at the bottom right corner of your ST editor window.

Now, in order to build with Python just go to Tools > Build. The output should be visible in the Console pane of ST3, which is in the bottom. If you run into any issues, make sure to check whether Tools > Build System is set to “Python”.

Further enhancements

If you wish to turn ST into a fully featured Python IDE, then you should install the Anaconda plugin (totally unrelated to the Anaconda Python distribution, btw). It enables autocompletion, code linting and a myriad of other fancy stuff.

To install it, just bring up the Command Palette with Ctrl+Shift+P , type “install”, hit Enter and search for “Anaconda”. Just hit Enter again to install, and restart ST to see the changes.

Stata

Getting Stata to work with ST3 requires a few steps, but it works very well when all is said and done. The process is quite different for Windows and macOS, so I’ve split this tutorial in two sections. I’m assuming that you already have Stata up and running (these steps will work with all versions > 10).

Windows

There are two Stata plugins for ST in Windows: StataEditor and Stata Enhanced. I tried both and finally preferred StataEditor, so that’s the one we’ll install and configure.

  1. Install StataEditor: in ST3, start the command palette with Ctrl+Shift+P , type “install” and hit Enter . Now search for StataEditor and just click on it to install.
  2. Install Pywin32: repeat the process described above, now installing the Pywin32 plugin.

Configure StataEditor: In ST3 go to Preferences > Package Settings > Stata​Editor > Settings — User. In this blank file you need to write down the path to your Stata executable and the version. For example, my configuration file in Windows looks like this:

Register Stata Automation library: go to the Stata executable for which you copied the path (e.g. StataMP-64.exe ) and create an shortcut for it. Now right click on this new shortcut and select “Properties”. In the “Target” field, add /Register at the end (with a preceding space). For example:

Apply and accept those changes and now right click again on the shortcut and choose to “Run as administrator”. Nothing is going to happen, but if you followed the instructions, it should be ready.

Restart ST3 and try opening an existing do-file (or creating a new one with .do extension). You should read “Stata” on the bottom right corner, and should be able to execute selections or complete do-files with Ctrl+D .

macOS

There are two packages available in Package Control to use ST3 as a Stata editor: Stata Enhanced and Stata Improved Editor. I’ve tried both and prefer Stata Improved Editor, mainly because it has a much finer control on the chunks you can execute. Shout out to Zizhong Yan for incorporating my comments in v1.1.2.

In order to Install Stata Improved Editor in ST3, start the command palette with Cmd+Shift+P , type “install” and hit Enter . Now search for Stata Improved Editor and just click on it to install. Reboot ST3, and that’s it!

CTRL + d sends the current line or the selected chunk to Stata. Also, you can execute the complete do-file with CTRL + SHIFT + d . The plugin has a lot of shortcuts and other nice features, so be sure to check out its repository to make the most out of it.

LaTeX

ST3 can be configured to work as a LaTeX editor pretty easily, specially if you’ve installed one of the “typical” TeX distributions: TeX Live, MiKTeX or MacTeX. If you don’t have LaTeX in your system, I suggest you get either TeX Live in Windows or MacTeX in MacOS. Just ensure you have one of these TeX distributions installed before proceeding.

Besides the LaTeX distribution, another important component is the PDF viewer… and forget about the defaults! On Windows I recommend you get Sumatra (thank me later for this awesome alternative to Adobe’s piece of crap). Just go to https://www.sumatrapdfreader.org/free-pdf-reader.html to download, and then install it.

On macOS I recommend Skim, a lightweight PDF viewer specifically tailored to reading and annotating scientific papers. Head over to http://skim-app.sourceforge.net/ to download and install it. After installing it make sure you go to Skim ‣ Preferences ‣ Sync and set the PDF-TeX Sync support Preset to Sublime, as shown here:

Sync options in Skim

Both of these viewers are super lightweight, work great with LaTeXTools and provide forward and inverse search capabilities, which is really handy (go here to read more about this feature).

Without regard of your operating system, you’ll want to install LaTeXTools, which adds extensive LaTeX support for ST3. Install by invoking the command palette ( Tools ‣ Command Palette ), type install and hit Return . Then search for LaTeXTools and hit Return again to install it. You should use the same method to install LaTeX-cwl , which allows for autocompletion of LaTeX commands:

LaTeX-cwl provides tab autocomplete

At this point you should run a system check with LaTeXTools, which ensures everything is well configured for LaTeX compilation. To do this, fire up the command palette ( Tools ‣ Command Palette ), search for LaTeXTools: Check System and hit Return . After a few seconds you should see a new tab with something like the following:

LaTeXTools system check

System is checked and we’re good to go! Don’t panic if ghostscript or magick are unavailable (like above): the former is used for equation and image previewing, while the latter is for previewing non-standard image formats.

So that’s it! You can now open any .tex file or create a new one, and compile it with Ctrl+B . If a dialogue pops up, just choose PDFLaTeX (or whatever you prefer) and LaTeX away!

Sublime text как запустить код

Sublime Text includes a command line tool, subl , to work with files on the command line. This can be used to open files and projects in Sublime Text, as well working as an EDITOR for unix tools, such as git and subversion.

Setup��

Some operating systems and installation methods will require a configuration change to make subl available on the PATH .

Windows��

On Windows, the command line helper is subl.exe . To use this from the Command Prompt or Powershell, the Sublime Text installation folder needs to be added to the Path environment variable:

Windows 10��

Open the Start Menu and type environ

Select the item Edit the system environment variables

Click the button Environment Variables at the bottom of the System Properties dialog

For the current user, select Path in the User variables for section

For all users, select Path in the System variables section

64bit installs are typically in C:\Program Files\Sublime Text\

32bit installs on a 64bit version of Windows will be in C:\Program Files (x86)\Sublime Text\

32bit installs on a 32bit version of Windows will be in C:\Program Files\Sublime Text\

Windows 8��

Press the Windows Key and type environ

Select the item Edit the system environment variables

Click the button Environment Variables at the bottom of the System Properties dialog

For the current user, select Path in the User variables for section

For all users, select Path in the System variables section

In the Variable value input, add an entry with the Sublime Text installation directory. If there is an existing value, add a ; before the Sublime Text directory.

  • 64bit installs are typically in C:\Program Files\Sublime Text\

  • 32bit installs on a 64bit version of Windows will be in C:\Program Files (x86)\Sublime Text\

  • 32bit installs on a 32bit version of Windows will be in C:\Program Files\Sublime Text\

Windows 7��

Open the Start Menu

Right-click on Computer and select Properties

Click on Advanced System Settings in the left-hand sidebar

Click the button Environment Variables at the bottom of the System Properties dialog

For the current user, select Path in the User variables for section

For all users, select Path in the System variables section

In the Variable value input, add an entry with the Sublime Text installation directory. If there is an existing value, add a ; before the Sublime Text directory.

  • 64bit installs are typically in C:\Program Files\Sublime Text\

  • 32bit installs on a 64bit version of Windows will be in C:\Program Files (x86)\Sublime Text\

  • 32bit installs on a 32bit version of Windows will be in C:\Program Files\Sublime Text\

To use subl , the Sublime Text bin folder needs to be added to the path. For a typical installation of Sublime Text, this will be located at /Applications/Sublime Text.app/Contents/SharedSupport/bin .

If using Bash, the default before macOS 10.15, the following command will add the bin folder to the PATH environment variable:

If using Zsh, the default starting with macOS 10.15, the following command will add the bin folder to the PATH environment variable:

Linux��

If Sublime Text is installed via one of the Linux Package Manager Repositories or a package, a subl symlink will automatically be installed into the /usr/bin/ directory.

If installing from a tarball, the sublime_text executable should be symlinked to subl , with a command such as:

The exact details of the symlink command will depend on the installation location. Most default PATH environment variable values should contain /usr/local/bin , so no further commands should be necessary.

Usage��

To see the available flags, run subl —help . The available flags will vary per operating system – the following example is from Linux:

Configuring as EDITOR��

To use Sublime Text as the editor for many commands that prompt for input, set your EDITOR environment variable:

Specifying -w will cause the subl command to not exit until the file is closed.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *