Python code in Sublime Text 3

We’ll learn how to download and install Sublime Text 3 and run Python scripts in the Sublime Text 3 editor. We will also examine the installation of packages. So let’s get started.

Running Python code in Sublime Text 3

Python code can be run using a variety of IDEs and text editors. It’s OK to use a text editor if you’re a newbie, but if you’re a developer, you’re probably aware of the value of IDEs. Although Sublime Text 3 is primarily a text editor, it has IDE-like features such as projects and “builds,” which allow you to run other applications from within the editor.

Now we’ll look at some valuable facts about the Sublime Text 3 editor.

Getting started programming with Sublime Text

  • It’s a developer’s lightweight editor.
  • Among developers, it is one of the most popular.
  • The best part about Sublime Text 3 is that it doesn’t take up much space on your computer and that working with it is convenient and comfortable.
  • It comes with built-in support for a variety of programming and markup languages.

Sublime Text 3 Cross-Platform Features

Sublime Text 3 is compatible with Windows, Linux, and Mac OS X.

You only need one license to use Sublime Text 3 on any machines you want to use it on, regardless of the operating system they are running.

Sublime Text 3 has a robust Python API that allows plugins to extend the capabilities of the editor.

Sublime Text has an Application Programming Interface (API) that programmers can use with the Python programming language to interface with its internals.

The editor comes with an embedded Python interpreter. While developing plugins, the embedded interpreter helps inspect the editor’s settings and fast testing API calls.

Split Layouts enable you to divide your files into multiple split screens. This is beneficial while working on the front end (HTML on one screen, CSS and/or JavaScript on another) or undertaking test-driven development (Python code on one screen, test scripts on another).

Vintage Mode gives you vi commands that you can use in ST3.

Tabs, which are similar to Chrome, make navigating and editing multiple files much easier.

The automatic reload of the previous session reopens all files and folders that were open when you last closed the editor. We have ST3 open all the time, with several projects available, so that when we restart the computer, the files and folders are automatically restored.

Code Snippets boost your productivity by allowing you to construct standard code with just a single keyword. Several default snippets are available. Open a new file, type lorem, and press Tab to see for yourself. A paragraph of lorem ipsum content should enough. In a Python file, typing defs and then pressing the tab will create a generic function.

Downloading and Installing Sublime Text 3

To begin, you must first download it. After that, sublime Text 3 is available for download. After that, you will see different version descriptions for different operating systems and the available ways for distribution.

You must now choose one as per your machine requirement. For instance, if your computer is 64-bit, download the 64-bit version and 32-bit version when the opposite is true. Go ahead and Install the downloaded file now by running the executable file if you are on windows. Or Linux repos such as .deb for Debian distros and .rpm.

Alternatively, on Linux based operating system like Ubuntu, we can install Sublime Text 3 via the terminal by running the following commands.

Step 1:

sudo apt update
sudo apt install apt-transport-https ca-certificates curl software-properties-common

The above commands will facilitate updating the apt package list and ensure that the necessary dependencies are collected from their sources and are available for use.

Step 2:

curl -fsSL https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add –

The use of the curl command is necessary for the importation of the repository’s GPG key. Successively, use the following command,

sudo add-apt-repository "deb https://download.sublimetext.com/ apt/stable/"

To add to your operating system’s software repository, the Sublime Text Apt repository.

Step 3:

sudo apt update
sudo apt install sublime-text

It is the final stage involving enabling and updating apt sources. Finally, it concludes by adding sublime text 3 to your system.

You are now ready to use.

Choosing a Direction

After installing it, you’ll need to set an environment variable to point to the python installation directory. If your path is already set, you can skip to the next section; otherwise, look at setting the path. The latter is a requirement, especially when running on the Windows operating system. However, it is not a show stopper because we are running it on the Ubuntu operating system.

Sublime Text 3 Customization

ST3 can be customized once it has been downloaded. First, Install the command-line tool subl.

Sublime Text offers a command-line tool called subl that allows you to open a single file, folders from the terminal, or an entire directory like TextMate’s mate command.

To enable this command, first establish a symbolic link to the subl.

sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/bin/subl

To make sure the link works, open Sublime by running the following command on the terminal.

subl

If it doesn’t work, you’ll need to include /bin in your path:

tuts@codeunderscored:~$ echo "export PATH=~/bin:$PATH" >> ~/.profile

You may now use the following commands to open a file or directory:

But, first, go to the current directory and open it.

tuts@codeunderscored:~$ Subl .

Create a codeunderscored.txt file and open it.

tuts@codeunderscored:~$ subl codeunderscored.txt

If the path contains spaces, double quotes must be used to enclose the complete path:

tuts@codeunderscored:~$ subl "~/Desktop/code underscored file.txt."

Open the help file to see all the commands:

tuts@codeunderscored:~$ subl --help
sublime subl --help feature on the terminal
sublime subl –help feature on the terminal

Installing Package Control

To begin using the numerous packages for expanding Sublime’s capability, you must first manually install Package Control, package management. You can use it to establish, delete, and update all other ST3 packages once it’s installed.

First, open the command palette using the following combination of keys simultaneously on both Windows and Linux.

ctrl+shift+p

or

cmd+shift+p

In Mac.

Subsequently, start typing install and keep going until you get to Package Control: Install Package. Press Enter when the dialog box appears to look for available packages.

To access the ST3 console, go to View > Show Console. First, copy the piece of code, then paste it into the console. Enter the code. ST3 should be restarted.

Here are a few more useful commands:

List

All of your installed packages are listed in List Packages.

remove

Remove Package is a command that deletes a specified package.

Upgrade

Upgrade Package improves the performance of a given package.

Upgrade/Overwrite All

All of your installed packages are upgraded when you choose Upgrade/Overwrite All Packages.

Themes

ST3 also allows you to adjust the general theme to fit your personality better. Make your own. If you’re not artistically inclined, you can use Package Control to get one of the many custom themes created by the Sublime community. ColorSublime is an excellent tool for previewing themes before installing them.

My faves are the ever-popular Soda Dark Theme, Predawn, and the minimalist Flatland.

After installing a theme, go to Sublime Text > Preferences > Settings – User: and edit your base settings. Or, if you wish to switch from one theme to the next, then go to Sublime Text > Preferences > Select Theme …

Select Themes in Sublime Text 3
Select Themes in Sublime Text 3

Goto

It is Sublime Text 3’s most powerful feature. With this capability, you can open files with just a few keystrokes.

It also allows you to jump to symbols, lines, or phrases in an instant.

To use this feature, press Ctrl+P and then type – If you want to open a file, type the first few letters of the file name. Suppose you want to jump to symbols, type @. If you wish to search anything within a file, type #, and if you directly access or jump to a particular line number, for instance, typing tp:54 will take you to line 54 of the file.

Palette of Commands

Sublime Text 3 has another proper function that allows you to do various functions such as sorting, modifying syntax, and changing identity settings.

The command palette will enable you to accomplish many things, such as manage sublime projects, change file syntax, and run package commands, among other things.

Hit ctrl+shift+p to open the command palette, then choose command and press Enter.
several options

open the command palette
open the command palette

It’s one of Sublime Text 3’s best features. For instance, you will alter many lines and manipulate files more quickly if you use this function.

It can be used as a rapid replacement for finding and replacing or applying the same set of modifications to numerous lines simultaneously.

Press Ctrl+Shift+L after selecting a block of text to break it into one selection per line, then Ctrl+D to determine the next occurrence of the selected word.

Go to the Definition page

The most awaited feature of Sublime Text 3 was the “Goto Definition” functionality. Goto Definition uses the symbol index provided by sublime Text.

To utilize Goto Definition, hit alt+g on your keyboard.

hit alt+g on your keyboard to access Goto
hit alt+g on your keyboard to access Goto

Snippets

Users can save blocks of commonly used code and attach keywords to them using Snippets. After that, the user can type the term and hit the tab to paste the code block whenever they need it.

Other Characteristics

Aside from the features listed above, Sublime Text 3 also includes the following:

  • Checking for misspellings
  • Save automatically
  • Keybindings that can be changed
  • Split editing with macros
  • Anything can be customized.

So now we’ll talk about using Sublime Text 3 to run Python scripts.

Run Your First Program using Sublime Run Python

Without question, Sublime Text is the most popular text editor among developers, and it can also be used to edit Python code. Now we’ll look at how to use it in Python.

Testing a simple program

Now we’ll examine how a Python program runs in Sublime Text 3. What we must do to achieve this is –

To begin, launch your sublime editor.

Create a new file using the procedures below. You can create a new file by initially accessing the to file menu then choosing New File or using ctrl+N,

After that, save it as testing.py. Note that the filename must end in.py. After that, write your code.

This example is the essential software that adds two numbers. As such, code is —

first_number = 12
second_number = 8

# addition of the two numbers
sum = float(first_number) + float(second_number)

# show the sum of the two numbers
print('The sum of {0} and {1} is {2}'.format(first_number, second_number, sum))

Putting the code to work

Choose Tool from the menu bar, then Build System, and then Python from the drop-down menu. Subsequently, access the menu “Tool” and choose the option “Build.” The latter is responsible for running your code. So, if we run the preceding code now, we’ll receive the following result.

using tools build to run the addition program
using tools build to run the addition program

Taking User Input

Now we’ll look at how to capture user input in sublime text 3.

In Python, taking input is a breeze. However, while working with sublime text 3, we need to make a few adjustments. So, let’s dive in and explore what they are –

Installing SublimeREPL Plugin

SublimeREPL is a Sublime Text plugin that allows you to run interactive interpreters in many languages from within a regular editor tab. It also allows you to use a telnet port to connect to a remote interpreter that is running (for example, Clojure/Lein).

SublimeREPL comes with built-in support for command history and transferring code from open buffers to interpreters for evaluation, making it possible to program interactively.

The sample program that runs on sublime is not intended to be used as a comment prompt; rather, it is intended for output. Therefore, PackageManager is used to accomplish this.

Copy the code from Package Control according to your sublime version.

Return to exquisite Text and select View->Show Console. Now you must put the copied code into this box and press enter. Your package will be installed in a few seconds.

running code on view show console
running code on view show console

Select Preferences->Package Control from the drop-down menu. You’ll see that there are a plethora of exquisite packages inside. Now select Install Packages from the drop-down menu.

A dialog will occur when you click Install Package, as seen below.

package controller with a list of packages to install
package controller with a list of packages to install

Now write SublimeREPL into this textbox, then select the first option and press Enter. The plugin will be installed as a result of this.

During the installation, you will see the installing package at the bottom.

To run the current file, navigate to Tools->SublimeREPL->Python->Python-RUN current file. This will run the existing file. So, let’s see what the result is.

RUN current file using SublimeREPL
RUN current file using SublimeREPL

It’s pretty extraordinary to be able to run Python scripts in Sublime Text 3. So instead of having to go to Tools->SublimeREPL->Python->Python-RUN current file every time, we can now create a shortcut.

Go to Preferences->Key Bindings and put your shortcut as illustrated in the “Keyboard Shortcuts” section below.

So now you don’t have to deal with a long-running procedure; all you have to do is hit ctrl+alt+b or something of the sort. That’s fantastic!!!!

Adding Python 3 as a build system

To get started, go to Tools -> Build System -> New Build Methodology.

new build system in sublime
new build system in sublime

You’ll notice that you can juggle between Python and Python 3 in your list of Build Systems if you have both versions. Python is installed automatically and is version 3.9. We’re going to include Python 3.

You’ll be taken to a new window called untitled. sublime-build after clicking New Build System as shown above.

The wording between the curly brackets needs to be changed. Remove the code between the brackets first. After that, copy and paste the code below:

"cmd": ["python3", "-i", "-u", "$file"],     
"file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",     
"selector": "source.python"

To indent the second and third lines, you may need to hit the tab. Now hit Command S to save the file. Rename the file to whatever you want your Build System to be called. Something succinct and easy to comprehend. MyBuild is the name we gave to ours. It’s important to note that the extension must MyBuild.sublime-build. Also, don’t deviate from the course. Sublime Text will automatically place it in the correct location.

Close the file once you’ve clicked save to return to your scratch.py file. Now pick MyBuild from Tools -> Build System (or whatever you named your Build System). If you don’t see your new build system, you may need to close and reopen Sublime Text.

Keyboard Shortcuts

Python makes it simple to create your custom commands using key bindings. For example, to set your shortcut, access the key bindings by going to Preferences →key bindings.
You can define your key bindings on the resultant empty list by entering the following code to cancel the build.

{"keys":["ctrl+alt+c"], "command":"cancel_build"},

You can also change any of the existing key bindings from the current key bindings. Then press Ctrl + S to save the changes. You may even need to restart sublime for the changes to use the shortcut to cancel the build.

Shortcuts on the Keyboard

Cmd+P

Cmd+P is used to search and open files rapidly. You can easily open a file by typing a portion of a path and filename within a project. This is useful for opening files in massive Django projects rapidly.

Ctrl+G

Go to Line No. Ctrl+G navigates to a specific line number in a currently open file.

Cmd+R

The Symbol Cmd+R makes it easier to find functions and classes within a file; press Cmd+R. Then, simply begin entering the name of the one you desire.

Cmd+Left and Cmd+Right

You can navigate within lines by pressing Cmd+Left to go to the beginning of a line and Cmd+Right to go to the end.

Ctrl+Shift+K

Delete the currently selected line The current line is deleted by pressing Ctrl+Shift+K.

Cmd+D

Multi-Edit is, without a doubt, my favorite keyboard shortcut: Select a word and then press Cmd+D to go on to the next one. Then press Cmd+D to choose the following same word, and so on. In addition, to generate a cursor for editing anywhere you click, press Cmd+Left Button.

To select a block of text, press the Option+Left Button combination. When formatting a CSV file, it’s ideal for reducing blank space.

Conclusion

We hope that this article was not just educative but also informative and thus valuable for your endeavors. As a result, we are confident that you could improve your workflow by combining some of the approaches and tricks we have mentioned herein, besides adopting some of the packages and custom settings with your own based on your unique preferences.

If you have any more questions or recommendations, we would be glad to hear them in the comments section below.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *