杰瑞科技汇

Python如何配置Sublime Text3高效开发?

Of course! Using Python with Sublime Text 3 is a very common and powerful workflow. Here’s a comprehensive guide covering everything from basic setup to running code and advanced features.

Python如何配置Sublime Text3高效开发?-图1
(图片来源网络,侵删)

Installation and Prerequisites

A. Install Sublime Text 3

If you haven't already, download and install Sublime Text 3 from the official website: https://www.sublimetext.com/3

B. Install Python

You need Python installed on your system.

  • Windows: Download from python.org. Crucially, check the box "Add Python to PATH" during installation.
  • macOS: Usually comes pre-installed. You can verify by opening Terminal and typing python3 --version. If not, use Homebrew: brew install python.
  • Linux: Usually comes pre-installed. Verify with python3 --version in the terminal.

C. Verify Python Installation

Open your system's terminal or command prompt and run:

# For Python 3
python3 --version
# Or on some systems, just 'python' might point to Python 3
python --version

This should show the installed version (e.g., Python 3.11.4).

Python如何配置Sublime Text3高效开发?-图2
(图片来源网络,侵删)

The Basics: Writing and Running Python Code

A. Create a Python File

  1. Open Sublime Text 3.
  2. Go to File > New File.
  3. Save the file with a .py extension (e.g., hello.py).

B. Write Your First Script

In the new file, type the classic "Hello, World!" script:

# hello.py
print("Hello, World!")

C. Run the Script

There are two primary ways to run your Python code from Sublime Text.

Method 1: Using the Terminal (Recommended)

This is the most flexible and common method.

  1. Save your Python file (hello.py).
  2. Open the Sublime Text built-in terminal:
    • Go to Tools > Build System > Python (this sets the correct interpreter).
    • Then, go to Tools > Build System > New Build System.... A new file will open. Replace its contents with this:
      {
          "cmd": ["python3", "-u", "$file"],
          "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
          "selector": "source.python"
      }
    • Save this file with a memorable name, like Python3.sublime-build, in the default location Sublime suggests. This tells Sublime to use python3 to run the file.
  3. Now, with your hello.py file open, simply press:
    • Ctrl + B (on Windows/Linux)
    • Cmd + B (on macOS)

The output Hello, World! will appear in a new "output" panel at the bottom of the Sublime window.

Python如何配置Sublime Text3高效开发?-图3
(图片来源网络,侵删)

Method 2: Using the SublimeREPL Plugin (For Interactive Sessions)

This plugin allows you to run an interactive Python shell inside Sublime Text, which is great for testing small snippets of code.

  1. Install Package Control:

    • If you don't have it, open Sublime and use the View menu to show the console (View > Show Console).
    • Paste the appropriate code for your OS from the Package Control website into the console and press Enter. This is the single most important plugin for Sublime.
  2. Install SublimeREPL:

    • Press Ctrl + Shift + P (or Cmd + Shift + P on Mac) to open the Command Palette.
    • Type Package Control: Install Package and press Enter.
    • In the new list that appears, type SublimeREPL and select it to install.
  3. Run SublimeREPL:

    • Open your Python file (hello.py).
    • Open the Command Palette (Ctrl+Shift+P).
    • Type SublimeREPL: Python - RUN current file and press Enter.
    • A new tab will open with an interactive Python shell, and your script will be executed in it.

Essential Plugins for Python Development

Package Control makes installing these a breeze. Use Ctrl+Shift+P -> Package Control: Install Package for each one.

Plugin Purpose Why You Need It
LSP (Language Server Protocol) The modern standard for IDE features. Provides real-time error checking, autocompletion, go-to-definition, and more. It's the foundation for a great Python experience in Sublime. Essential. Turns Sublime from a text editor into a lightweight IDE. It supports many languages, including Python.
Anaconda A powerful all-in-one package for Python development. A great alternative to LSP, especially if you want a simpler setup. It provides linting, autocompletion, and code navigation.
Black Formatter Integrates the Black code formatter. Automatically formats your Python code to be clean and consistent, adhering to the PEP 8 style guide. Run it with Ctrl+Shift+P -> Black: Format File.
Flake8 Integrates the Flake8 linter. Scans your code for style and syntax errors (violations of PEP 8). Warnings will appear in the editor, helping you catch mistakes early.
SublimeJEDI Provides intelligent autocompletion. Works well with Anaconda or on its own. It understands your code and suggests variables, functions, and modules as you type.
DocBlockr Simplifies writing docstrings. Automatically generates PEP 257 compliant docstrings for your functions and classes. Just type above a function and press Tab.

Setting Up a Project with Virtual Environments

Using virtual environments is a best practice to manage project dependencies. Here's how to set it up with Sublime.

  1. Create a Project Folder:

    mkdir my_python_project
    cd my_python_project
  2. Create a Virtual Environment:

    # For Python 3, it's best to use 'venv'
    python3 -m venv venv

    This creates a venv folder in your project.

  3. Activate the Environment:

    • Windows: venv\Scripts\activate
    • macOS/Linux: source venv/bin/activate You'll see (venv) at the beginning of your terminal prompt, indicating it's active.
  4. Install Packages: Now, any pip install will go into this isolated environment.

    pip install requests pandas
  5. Tell Sublime to Use the Virtual Environment's Python:

    • Open your project in Sublime (File > Open Folder...).
    • Open the Command Palette (Ctrl+Shift+P).
    • Select LSP: Select LSP.
    • Choose Pylsp (if using LSP) or configure your build system to point to the Python interpreter inside the venv folder.
      • Windows: venv\Scripts\python.exe
      • macOS/Linux: venv/bin/python
    • You can create a new build system (as in section 2.C) that uses this specific path.

Now, Sublime's linter, autocompletion, and runner will all use the packages from your venv.


Debugging Python Code

Sublime Text is not a full-fledged debugger like VS Code or PyCharm, but you can add basic debugging capabilities.

Option A: Using the pdb Module (Built-in)

Python has a built-in debugger called pdb. You can insert breakpoints directly into your code.

  1. In your Python script, import pdb and add a breakpoint where you want to pause execution:

    # my_script.py
    import pdb
    def add(a, b):
        result = a + b
        pdb.set_trace()  # Execution will stop here
        return result
    print(add(5, 3))
  2. Run the script using the build system (Ctrl+B).

  3. Execution will pause at pdb.set_trace(). A new console will appear at the bottom where you can interact with the debugger using commands like:

    • n (next): Execute the current line and move to the next.
    • c (continue): Continue execution until the next breakpoint.
    • l (list): Show the code around the current line.
    • p <variable_name> (print): Print the value of a variable.

Option B: Using the Sublime Debugger Plugin

For a more graphical debugging experience, you can use a plugin like SublimeDebugger. This requires more setup but provides a more traditional debugger interface with breakpoints, variable inspection, etc. You would install it via Package Control.


Summary Workflow

  1. Setup: Install Sublime Text 3 and Python. Install Package Control.
  2. Install Core Plugins: Install LSP for a modern IDE experience.
  3. Create Project: Make a folder for your project and open it in Sublime.
  4. Virtual Environment: Create and activate a venv inside your project folder. Install project dependencies.
  5. Configure: Tell Sublime's LSP or build system to use the Python interpreter from your venv.
  6. Code: Write your Python code. Enjoy real-time linting and autocompletion from LSP.
  7. Run: Press Ctrl+B to quickly run your script and see the output.
  8. Format/Lint: Use Black: Format File to format your code and rely on the linter to catch errors.
  9. Debug: Use pdb.set_trace() for simple debugging when needed.
分享:
扫描分享到社交APP
上一篇
下一篇