杰瑞科技汇

如何在mac上用sublime运行python代码?

Of course! Using Sublime Text for Python development on a Mac is a fantastic and popular choice. It's lightweight, fast, and highly customizable.

Here is a comprehensive guide covering everything from setup to best practices, tailored for macOS.


Why Sublime Text for Python?

  • Speed: It's incredibly fast, even with large files and projects.
  • Lightweight: It doesn't hog system resources like some other IDEs.
  • Powerful Editing: Features like multiple cursors, split editing, and "Go to Anything" make coding a breeze.
  • Customizable: You can change everything from the theme to keybindings with simple configuration files.
  • Cross-Platform: The same setup works on Windows and Linux.

Prerequisites: Install Python and a Package Manager

Before you start, you need Python on your system. Modern macOS versions come with Python pre-installed, but it's often an older version and managed by the system, so it's best to install your own.

Step 1: Install Python

The best way to manage Python versions on a Mac is with Homebrew.

  1. Install Homebrew (if you don't have it). Open the Terminal app (you can find it in Applications/Utilities or search for it with Spotlight) and paste this command:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  2. Install Python 3 using Homebrew:
    brew install python

    This will install the latest stable version of Python 3 and pip (Python's package installer) in a non-system location, avoiding permission issues.

Step 2: Verify the Installation

In your Terminal, run these commands to make sure everything is working:

# Check the version of Python 3
python3 --version
# Check the version of pip
pip3 --version

You should see version numbers printed. Important: You'll use python3 and pip3 in your terminal to distinguish from the system's Python.


Installing Sublime Text

  1. Go to the Sublime Text official website.
  2. Download the latest build for macOS.
  3. Drag the Sublime Text.app icon into your Applications folder.
  4. Open it. You'll get a nag screen to buy it, but it's a fully functional unlimited trial.

Essential Sublime Text Setup for Python

Now, let's configure Sublime Text to be a powerful Python environment.

Step 1: Install Package Control

Package Control is the package manager for Sublime Text. It's the single most important thing you'll install.

  1. Open Sublime Text.
  2. Go to the View > Show Console menu. A console panel will appear at the bottom.
  3. Copy the appropriate code for your Sublime Text version (3 is standard) from the official Package Control installation page and paste it into the console.
  4. Press Enter. You'll see a "Package Control: Installed" message at the bottom. Restart Sublime Text.

Step 2: Install Essential Packages

Now that you have Package Control, you can easily install packages.

  1. Open the Command Palette: Cmd+Shift+P.
  2. Type install and select "Package Control: Install Package".
  3. A list will appear. Start typing the name of the package you want to install and select it from the list. Here are the essentials for Python:
Package Name What it Does Why You Need It
LSP Language Server Protocol client. This is the modern, all-in-one package for code intelligence. Provides code completion (IntelliSense), real-time error checking, and go-to-definition. This replaces older, separate packages.
LSP-pyright A Python language server using Pyright (Microsoft's static type checker). This is the engine that powers LSP for Python. It gives you powerful, fast, and accurate code analysis.
Anaconda A very popular, all-in-one package for Python development. An alternative to LSP. It provides code completion, linting, code formatting, and a great "IDE Experience" out of the box. (Choose either LSP or Anaconda, not both)
SublimeREPL A Read-Eval-Print Loop (REPL) inside Sublime Text. Allows you to run Python code, test functions, and debug interactively without leaving the editor.
GitGutter Shows git diff markers in the gutter (the space on the left of the line numbers). See which lines have been added, modified, or deleted at a glance.
DocBlockr Helps you write documentation for your functions and classes. Automatically generates docstring templates for you.

Example Installation Workflow:

  1. Press Cmd+Shift+P
  2. Type Install Package
  3. Type LSP and press Enter.
  4. Wait for it to install.
  5. Repeat for LSP-pyright, SublimeREPL, etc.

Step 3: Configure LSP (Recommended Modern Setup)

  1. After installing LSP and LSP-pyright, restart Sublime Text.
  2. LSP should automatically detect and configure pyright for .py files.
  3. You can check the status by opening a Python file and looking at the bottom-right corner. It should say pyright or LSP: pyright [active].

Step 4: Set Up a Build System

A "Build System" tells Sublime Text how to run your code. We need to create one that uses python3.

  1. Go to Tools > Build System > New Build System...

  2. A new, empty file will open. Delete the default content and paste this:

    {
        "cmd": ["python3", "-u", "$file"],
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "selector": "source.python"
    }
    • "cmd": ["python3", "-u", "$file"]: This is the command. It runs python3 with the -u flag (unbuffered output) on the current file ($file).
    • "file_regex": Helps Sublime Text parse error messages from the terminal and link them to the correct line in your code.
    • "selector": "source.python": This build system is only used for Python files.
  3. Save the file. Sublime Text will suggest a name like Python3.sublime-build. Save it in the default location (your Packages/User directory).

  4. Now, go to Tools > Build System and you should see Python3 at the bottom of the list. Select it to make it the default.


Your Workflow: Writing and Running Python Code

Let's put it all together.

  1. Create a File: In Sublime Text, create a new file and save it as hello.py.

  2. Write Code:

    # hello.py
    def greet(name):
        """A simple greeting function."""
        return f"Hello, {name}!"
    if __name__ == "__main__":
        user_name = input("What is your name? ")
        message = greet(user_name)
        print(message)
  3. Run the Code:

    • Make sure your Python3 build system is selected (Tools > Build System > Python3).
    • Press Cmd+B (Build).
    • The output will appear in a new panel at the bottom of the screen. You can type your name and press Enter to interact with the input() function.
  4. See Code Intelligence:

    • As you type grea, you should see a pop-up suggesting the greet function (thanks to LSP/Anaconda).
    • If you make a syntax error like print("hello", you'll see a red underline and an error message in the status bar.

Bonus Tips for a Better Experience

  • Snippets: Create your own code templates. Go to Tools > Developer > New Snippet... to create a snippet for things like if __name__ == "__main__":.
  • Themes and Color Schemes: Install new themes and color schemes via Package Control. Search for Theme or Color Scheme and install one you like (e.g., Material Theme, Solarized). You can enable them via Preferences > Color Scheme.
  • Key Bindings: Customize keyboard shortcuts. Go to Preferences > Key Bindings - User to remap keys. For example, you could make Ctrl+R run the file instead of Cmd+B.
  • Side Bar Enhancements: This package enhances the default file sidebar, allowing you to easily open a terminal in the current project folder, copy file paths, and more.

Summary: The Path to a Great Python Environment

  1. Install Python 3 via brew install python.
  2. Install Sublime Text.
  3. Install Package Control via the console.
  4. Install Packages via Cmd+Shift+P: LSP, LSP-pyright, SublimeREPL, GitGutter.
  5. Create a Build System (Tools > Build System > New...) that uses python3.
  6. Write code and run it with Cmd+B.

With this setup, you have a fast, efficient, and powerful Python development environment on your Mac. Happy coding

分享:
扫描分享到社交APP
上一篇
下一篇