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

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

  • автор:

How to run python codes in sublime text editor

Siva Santosh S

The first thing to run a python code in sublime text editor, is to install the sublime text editor, which we may get from the official website of sublime. I’m leaving a link here, https://www.sublimetext.com/3 download the required version depending upon your OS and your system configuration.

Once the above step is done, write a piece of code and save it with the extension of (.py format). Now if you observe it clearly the color of your font changes. Here, in my case I saved the file with test.py name.

The additional tip, before running the code make sure you had made these changes

How do I run Python code from Sublime Text 2?

I want to set up a complete Python IDE in Sublime Text 2.

I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ?

ragnarswanson's user avatar

16 Answers 16

Tools -> Build System -> (choose) Python then:

To Run:

This would start your file in the console which should be at the bottom of the editor.

To Stop:

You can find out where your Break key is here: http://en.wikipedia.org/wiki/Break_key.

Note: CTRL + C will NOT work.

What to do when Ctrl + Break does not work:

Preferences -> Key Bindings — User

and paste the line below:

Now, you can use ctrl+shift+c instead of CTRL+BREAK

Edit %APPDATA%\Sublime Text 2\Python\Python.sublime-build

Change content to:

change the «c:\python27» part to any version of python you have in your system.

On Mac OS X, save your file with a .py extension. Press ⌘ + B . It runs in a window below.

enter image description here

Heinrich Cloete's user avatar

bobobobo's user avatar

To RUN press Ctrl B (answer by matiit)

But when Ctrl B does not work, Sublime Text probably can’t find the Python Interpreter. When trying to run your program, see the log and find the reference to Python in path.

The point is that it tries to run python via command line, the cmd looks like:

If you can’t run python from cmd, Sublime Text can’t too.
(Try it yourself in cmd, type python in it and run it, python commandline should appear)

SOLUTION

You can either change the Sublime Text build formula or the System %PATH% .

To set your %PATH% :
*You will need to restart your editor to load new %PATH%

Run Command Line* and enter this command: *needs to be run as administrator
SETX /M PATH "%PATH%;<python_folder>"
for example: SETX /M PATH "%PATH%;C:\Python27;C:\Python27\Scripts"

OR manually: (preferable)
Add ;C:\Python27;C:\Python27\Scripts at the end of the string. Setting Path in Win7

To set the interpreter’s path without messing with System %PATH% see this answer by ppy.

How to Run Python Program in Sublime Text

In this tutorial you will learn how to run python program in sublime text in windows.

Just follow below steps to configure sublime text. The whole process is divided into two parts.

Part 1: Setting Path

First of all you have to set the path of python installation directory in environment variable. You can skip this step if it is already done.

1. Copy the path of python installation directory. In my case it looks like as shown below.

C:\Users\TCP\AppData\Local\Programs\Python\Python36-32

Note: Here TCP is the user name of my computer. It will be different in your case.

2. Now right click on Computer and click on Properties option. Then select Advance system settings in left sidebar.

3. Now click on Environment Variables and then under System variables select variable with name Path.

4. Click Edit button and then in Variable value field go to end and type semicolon and then paste the path of python directory that you copied. See below screenshot.

How to Run Python Program in Sublime Text 1

5. Finally click on all OK buttons to save the settings.

Part 2: Install SublimeREPL Plugin

For taking input from user in sublime text we need a plugin named as SublimeREPL. So follow below steps to install it.

1. Go to below link and copy the code according to your sublime text version.

How to Run Python Program in Sublime Text 2

2. Open sublime and go to View > Show Console. Then in console box at bottom paste the code that you have just copied and press enter. Wait for few seconds, it will install required packages.

How to Run Python Program in Sublime Text 3

3. Then go to Preferences > Package Control > Package Control: Install Package.

How to Run Python Program in Sublime Text 4

4. In textbox type SublimeREPL and select it to install the plugin. After installation restart sublime text.

How to Run Python Program in Sublime Text 5

5. Now got to Tools > Build System > New Build System. A new file will open, just paste the following code in it.

Как вывести результат программы Python в редакторе Sublime Text 3?

Можно конечно было запустить отдельно консоль (cmd), в ней прописать путь к интерпретатору Python и путь к Вашей программе, чтобы она выполнилась. Каждый раз это делать не удобно. Сделаем так, чтобы код программы Python можно было выводить в самом редакторе Sublime Text 3.

1. Запускаем Sublime Text 3 и заходим в меню.

Sublime cmd

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 Sublime cmd

После этих нехитрых действий, запускаем Вашу программу на 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 будет являться весомым преимуществом.

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

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