How to run python code in Sublime Text 3?
So I’m trying to run python code from Sublime Text 3, but I’m not sure how. Even if it was only from the console, that would be fine. Anybody know how.
![]()
8 Answers 8
Tools->Build System->Python or Ctrl+B
Need to install package to run python from sublime Python + Sublime
Try Anaconda plugin which will help you to run python on sublime
![]()
You can use this package in sublime text: https://packagecontrol.io/packages/Terminal to open a terminal at the specific file or folder.
Sublime Text 3 will run your python code inside the integrated console when you use Ctrl + B
if you want to run your code at own terminal, but still get some error information inside to integrated console, you need to build your own builder, or use plugins.
This answer is for fellow googlers who want to run python scripts within their sublime. As other answers explains, all you need is a sublime build system, here after a bit of struggle I got it worked for Linux Systems.
This is by far the simplest I believe. Hope it helps.
If you need non-interactive Build System, just follow the Official Guide.
If you plan to run code that contains something like input(), or you have any other way of interacting with your program you would need additional setup — Plugin + simple config.
The steps of having proper/full build system are:
- Install "Package Control":
Win/Linux: ctrl+shift+p, Mac: cmd+shift+p ▶ Type: Install Package Control ▶ ENTER
- Install Terminus via Package Control:
Win/Linux: ctrl+shift+p, Mac: cmd+shift+p ▶ Type: Package Control: Install Package ▶ ENTER ▶ Type: Terminus ▶ ENTER
- Create Build System for Python
Tools ▶ Build System ▶ New Build System… menu item or the Build: New Build System ▶ Paste one of the following sections and edit respectively.
For Windows, obviously you should change the path to your Python:
For Mac/Linux, do not forget to change the path to your Python.:
- Name the file e.g: Python Custom.sublime-build
- Select the newly created Build System:
Tools ▶ Build System ▶ Python Custom 6. Execute your code: Ctrl/CMD + B
Sublime text как запустить код
Войти
Авторизуясь в LiveJournal с помощью стороннего сервиса вы принимаете условия Пользовательского соглашения LiveJournal
Чтобы запускать тестовые куски кода javascript прямо в текстовом редакторе sublime text, не открывая браузер для просмотра вывода функции, эта короткая инструкция может быть полезной.
Вот так выглядит полученный результат:

Есть несколько способов сделать это, однако, дабы не рассматривать их все, остановимся на кроссплатформенном варианте. Поможет в этом Node.js.
Предполагается, что вы уже используете node и имеете представление о том, что это. Если это не так, вам сюда.
Далее обратимся непосредственно к текстовому редактору и создадим скрипт для новой системы сборки: “Tools” -> “Build System” -> “New Build System”.
Сохраните файл под именем node.sublime-build и убедитесь, что в пользовательских настройках правильно указан путь к Node.js.
Готово. Запуск системы сборки осуществляется командой, которая указана в меню Tools -> Build . Для windows и linux это ctrl + B . Убрать окно можно дважды нажав esc .
Как вывести результат программы Python в редакторе Sublime Text 3?
Можно конечно было запустить отдельно консоль (cmd), в ней прописать путь к интерпретатору Python и путь к Вашей программе, чтобы она выполнилась. Каждый раз это делать не удобно. Сделаем так, чтобы код программы Python можно было выводить в самом редакторе Sublime Text 3.
1. Запускаем Sublime Text 3 и заходим в меню.

2. Удаляем содержимое и заменяем на:
<
«cmd»: [«C:\\python33\\python.exe», «-u», «$file»],
«file_regex»: «^[ ]*File \»(. *?)\», line ([0-9]*)»,
«selector»: «source.python»
>

Обратите внимание, на форматирование кода табуляцией!
3. Сохраняем файл Как, не изменяя дериктории. Имя можно задать любое. Рекомендуемое название файла «PythonCMD». Закрываем только что редактируемый файл (вкладку) PythonCMD. Чтобы у нас был пустой редактор без вкладок.
4. Выбираем в настройках только что созданный конфигурационный файл Tools -> Build Systems -> PythonCMD.
Если вы используете редактор Sublime Text 3 только для написания Python кода, тогда Вам в дальнейшем нет необходимости менять настройки. Если вы используете редактор для написания кода на других языках, тогда для запуска кода, Вам необходимо будет менять систему запуска в Tools.

После этих нехитрых действий, запускаем Вашу программу на Python (ctrl+b или F7). Результат будет выводится в окне редактора.
В сети есть множество решений про кодировку, вывод результатов в консоле (cmd), использование плагинов (SublimeREPL) итд. Как именно вывести результат именно в самой консоле редактора Sublime Text, а не в консоле Windows cmd, решений не было. Во всяком случаи, я их не нашел. Поэтому, предлагаю вам свое решение.
Как установить SublimeREPL и другие плагины, опишу отдельно. Для первого старта работы с Sublime Text 3 и Python выше описанных настроек достаточно.
[ Рекоммендация. ]
Если вы хотите научиться программировать, стать/быть программистом, рекомендую установить Ubuntu (Linux).
Возможно не стоит сразу сносить Windows и ставить только Ubuntu. Ubuntu можно установить как дополнительную ОС. И запускать только тогда, когда требуется программировать. Когда привыкните к Linux, узнаете преимущества, можно будет смело переходить на Linux.
. Не забудьте сохранить все важные файлы на отдельном флэш носителе.
Для тех, кто любит играть в игры. Под Ubuntu есть Steam и много других интересных игрушек.
В ближайшее время Valve выпускает свою Steam OS основанную на Linux.
Для Python под Linux есть интересная библиотека PyGame, можно разрабатывать свои 2D игры. Для 3D есть другие библиотеки.
На Ubuntu/Linux по умолчанию установлен Python и другие языки программирования.
Если Вы хотите работать программистом, то посмотрите вакансии. Все крупные компании ищут программистов и айтишников со знанием Linux в первую очередь. Или знание Linux будет являться весомым преимуществом.
Sublime Text 4
Using Python in Sublime Text
As macOS comes with Python pre-installed, Sublime Text can usually run it out-of-the-box:
- Using the Sublime Text Build System:
- Open a Python script (a file with the “.py” extension) in Sublime Text then try to build it using either the menu (Tools > Build) or the keyboard shortcut (Cmd+B)
- If a box appears in the lower part of the screen with text detailing information about your build, then Sublime Text has successfully run Python on your script
- If no box appears and you see the words “No Build System” in the very bottom-left of the screen (in the bottom grey bar) then it hasn’t worked and you need to follow the “Creating a Python Build System” instructions below
- A Sublime Text package called SublimeREPL can be installed and used to run Python. You may prefer it to the Build System or you may not, it’s up to you.
- This can be installed through Sublime Text’s Package Control:
- If you do not have Package Control yet, first install it either from the menu (Tools > Install Package Control…) or from the Command Palette (Tools > Command Palette… [or use the keyboard shortcut Shift+Cmd+P], search for “Install Package Control” and press Enter)
- Once you have Package Control installed, open the Command Palette again, search for “Package Control: Install Package”, hit Enter, search for “SublimeREPL” and hit Enter again
- Terminus is another Sublime Text package. It opens a terminal as a window in Sublime Text which, just like a regular terminal, can be used to run Python on a file.
- Install Terminus from Package Control as detailed above: open the Command Palette either from the menu (Tools > Command Palette…) or via the keyboard shortcut (Shift+Cmd+P), search for “Package Control: Install Package”, Enter, search for “Terminus”, Enter again
- It’s useful to create a custom key binding for Terminus: from the menu go Sublime Text > Preferences > Package Settings > Terminus > Key Bindings and on the right-hand side (Default (OSX).sublime-keymap) add the following to the JSON file (leave the final comma out if it’s the last key binding in the file):
- Now, you can press Shift+Alt+T to get a terminal window which you can use to run Python like so:
However, even though Python can now be used from within Sublime Text there are a couple of things to be aware of:
Troubleshooting
When changing settings, always close-and-open Sublime Text and/or your terminal to let the changes take effect.
- What version of Python is being used? And is it Python 2 or Python 3?
- Check by running the following script:
- If you have multiple copies of Python installed — eg one in /Library/Frameworks/ and another in /usr/local/bin/ — it will probably not be clear which one Sublime Text is using
- Check by running this script:
Creating a Python Build System
To create a custom build file for Python 3.11:
- Tools > Build System > New Build System…
- Replace everything with the following:
- Save it as Python 3.11.sublime-build in the default location (which will be /Users/<username>/Library/Application Support/Sublime Text 3/Packages/User if you’re using Sublime Text 3 or initially installed Sublime Text 3 and have since upgraded to 4)
- Open a Python file in Sublime Text and go Tools > Build With… (keyboard shortcut: Shift+Cmd+B) > Python 3.11
- You should only have to do this once as the ‘build with’ command sets the default build system for a file type. From now on you should be able to just do Tools > Build (Ctrl+B)
For the more generic ‘Python 3’ (which will use a version of Python 3, not necessarily the latest one you have installed) you can use the following (for any other version of Python, just replace the python3 with the version you want — provided you have it installed, of course):
Ubuntu
Ubuntu 22.04
Setup
- Running Python files in Sublime Text usually works out-of-the-box:
- Open a Python file (a file with a .py extension) in Sublime Text
- From the menu bar, go to Tools > Build (or press Ctrl+B). This should run the Python script.
Changing the Version of Python used by Sublime Text
- The Sublime Text Python Build System works by running the python3 command on the file that is currently open. By default, this will be Python 3.10.6 because that is the version Ubuntu 22.04 comes pre-installed with. If you want to change that (eg if you have Python 3.11 installed and working and want Sublime Text to use that) you will need to create a new build system:
- Go to Tools > Build System > New Build System…
- Replace all text with:
Using SublimeREPL
- Install SublimeREPL via Package Control (Ctrl+Shift+P > search for “install package” > search for “SublimeREPL”)
- Tools > SublimeREPL > Python > Python — RUN current file (you can optionally create a user key binding to do this via a keyboard shortcut)
- Shift+Alt+8 creates a lower window which you can drag the Python output console to
- Troubleshooting:
- If the code runs fine but you get the following window:
- Open Preferences > Package Settings > SublimeREPL > Settings — User
- Enter the following:
Using Terminus
Python files can also be run ‘manually’ from a Terminus terminal, look here for more info on installing that.