Of course! Here is a comprehensive guide to setting up and using Python on a Mac with Sublime Text.
This guide is broken down into several key sections:
- Prerequisites: Making sure you have Python installed.
- Sublime Text Setup: Installing Sublime Text and essential packages.
- Writing & Running Code: The core workflow of writing and executing Python scripts.
- Advanced Features: Using Sublime Text as a more powerful IDE (linting, debugging, etc.).
- Troubleshooting: Common problems and their solutions.
Prerequisites: Check Your Python Installation
Most modern macOS versions (High Sierra and later) come with Python 3 pre-installed. It's crucial to know which version you have and where it lives.
Step 1: Open the Terminal
- Press
Cmd + Spaceto open Spotlight Search. - Type
Terminaland press Enter.
Step 2: Check for Python 3
In the Terminal, type the following command and press Enter:
python3 --version
or
which python3
- If you see a version number (e.g.,
Python 3.9.6) and a path (e.g.,/usr/bin/python3), you're all set! You have the system's Python 3 installed. - If you get an error like
command not found: python3, you need to install Python. The easiest way is to use the official installer from the Python website. Make sure to check the box for "Install pip for all users" and "Add Python to PATH" (though on Mac, it's often better to usepython3in the terminal).
Important Note: On macOS, you should use the
python3command in your terminal to ensure you are using the modern Python 3 interpreter, not the older, deprecated Python 2 (python).
Sublime Text Setup
Now let's get Sublime Text ready for Python development.
Step 1: Install Sublime Text
If you haven't already, download and install Sublime Text from the official website: https://www.sublimetext.com/
Step 2: Install the Package Control Manager
Package Control is the most important plugin for Sublime Text. It's a package manager that lets you easily install other plugins.
-
Open Sublime Text.
-
Open the Console: Go to the menu
View > Show Console. -
Copy the code below that matches your Sublime Text version and paste it into the console. Press Enter.
- For Sublime Text 4:
import urllib.request,os,hashlib; h = '6f4c264a24d933ce70df5dedcf1dcaee' + 'e330c653d4c3aa416f786ccbce4f8961'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by) - For Sublime Text 3:
import urllib.request,os,hashlib; h = '6f4c264a24d933ce70df5dedcf1dcaee' + 'e330c653d4c3aa416f786ccbce4f8961'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)
- For Sublime Text 4:
-
Restart Sublime Text. You should now be able to open the Command Palette with
Cmd + Shift + Pand see "Package Control: Install Package" as an option.
Step 3: Install Essential Python Packages
-
Open the Command Palette (
Cmd + Shift + P). -
Type
Package Control: Install Packageand press Enter. -
Wait for the list to load, then search for and install the following packages:
-
Anaconda: This is the "all-in-one" package for Python development. It provides:
- Code Completion: Autocompletion as you type.
- Linting: Checks your code for style and syntax errors using tools like Pylint, Flake8, or Pyflakes.
- Code Formatting: Automatically formats your code (e.g., with
yapforautopep8). - Tooltips: Shows you function signatures and docstrings.
-
SublimeREPL: Allows you to run an interactive Python shell inside Sublime Text. This is fantastic for quick testing and exploration.
-
Terminality: A simple and reliable way to open a terminal at the current file's or project's directory.
-
Writing & Running Python Code
This is the basic workflow you'll use 90% of the time.
Step 1: Create a Python File
- In Sublime Text, go to
File > New File. - Save the file with a
.pyextension (e.g.,hello.py). Sublime Text will automatically recognize it as a Python file and apply syntax highlighting.
Step 2: Write Your Code
# hello.py
name = input("What is your name? ")
print(f"Hello, {name}! Welcome to Sublime Text.")
Step 3: Run the Script from Sublime Text
The easiest way to run a script is to use a simple build system.
-
Go to
Tools > Build System > New Build System.... -
A new file will open. Delete the default content and paste the following code:
{ "cmd": ["python3", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python" }"cmd": This tells Sublime Text to run thepython3command on the current file ($file). The-uflag forces unbuffered output, which is better for interactive scripts."file_regex": This helps Sublime Text parse error messages and link them directly to the line in your code."selector": This tells Sublime Text to use this build system only for files with thesource.pythonsyntax (i.e.,.pyfiles).
-
Save this file with a memorable name, like
Python3.sublime-build, in the default location that Sublime Text suggests (usually aPackages/Userfolder). -
Now, to run your script, simply save your Python file (
Cmd + S) and then pressCmd + B. The output will appear in a new "output" pane at the bottom of the screen.
Advanced Features (Making it an IDE)
Linting with Anaconda
Anaconda's linting is fantastic for catching bugs and enforcing style.
- It should work automatically once you install Anaconda.
- You'll see red squiggly lines under code that has errors and yellow lines for style violations.
- You can see the error message by hovering your mouse over the underlined text.
- To configure it, go to
Preferences > Package Settings > Anaconda > Settings - Userand customize the linters you want to use (e.g., Pylint, Flake8).
Interactive Shell with SublimeREPL
- Open your Python file.
- Open the Command Palette (
Cmd + Shift + P). - Type
SublimeREPL: Python - RUN current fileand press Enter. - A new tab will open with an interactive Python shell, and your script will be executed in it. You can then type more commands to see the state of your program.
Debugging with the Python Debugger (pdb)
While Sublime Text doesn't have a built-in graphical debugger, you can easily use the standard Python pdb module.
-
In your Python code, import the debugger and set a breakpoint where you want to stop:
import pdb def add(a, b): pdb.set_trace() # This is the breakpoint result = a + b return result print(add(5, 3)) -
Run your script using
Cmd + B. -
The execution will pause at
pdb.set_trace(). The output panel will become an interactive debugger console where you can type commands like:n(next): Execute the current line and move to the next.c(continue): Continue execution until the next breakpoint or the end of the program.l(list): Show the code around the current line.p <variable_name>(print): Print the value of a variable.
Troubleshooting
Problem: "Command not found: python3" when building.
- Cause: Sublime Text can't find the
python3executable in the system's PATH. - Solution:
- Find the full path to your
python3executable by runningwhich python3in your Terminal. It will likely be/usr/bin/python3or/opt/homebrew/bin/python3(if you installed via Homebrew). - Edit your Python3 build system (
Packages/User/Python3.sublime-build). - Change the
"cmd"line to use the full path:"cmd": ["/usr/bin/python3", "-u", "$file"]
- Find the full path to your
Problem: Linter is showing errors but I think my code is fine.
- Cause: Anaconda might be using a linter that has strict rules (e.g., Pylint).
- Solution: You can disable or change the linter in the Anaconda settings. Go to
Preferences > Package Settings > Anaconda > Settings - Userand modify the"linters"section. For example, to disable Pylint, you might add"pylint": {"enabled": false}.
Problem: I want to use a virtual environment.
-
Cause: You want to isolate your project's dependencies.
-
Solution: The best way is to use the Terminality package.
-
Open your project folder in Sublime Text (
Project > Open Folder). -
Open the Command Palette and run
Terminality: Open. -
This will open a terminal tab inside Sublime Text, automatically
cd'd into your project directory. -
In that terminal, create and activate your virtual environment as you normally would:
# Create the virtual environment python3 -m venv myenv # Activate it source myenv/bin/activate # Now you can install packages pip install requests
-
With the virtual environment active, run your script with
Cmd + B. Sublime Text will now use thepythonfrom yourmyenvdirectory.
-
