杰瑞科技汇

Sublime Text 如何配置 Python 开发环境?

Of course! Using Sublime Text for Python development is a fantastic choice. It's lightweight, incredibly fast, and highly customizable through plugins. This guide will walk you through everything you need to get a powerful Python development environment up and running.

Sublime Text 如何配置 Python 开发环境?-图1
(图片来源网络,侵删)

Why Use Sublime Text for Python?

  • Speed: It's famously fast, even with large files.
  • Simplicity: The interface is clean and uncluttered.
  • Powerful Search & Navigation: "Goto Anything" (Ctrl+P) and "Goto Definition" are essential for productivity.
  • Customization: The entire editor can be tailored to your needs with packages.
  • Cross-Platform: Works on Windows, macOS, and Linux.

Part 1: Installation and Setup

Install Sublime Text

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

Install the Package Control Package Manager

This is the most important first step. Package Control is the package manager for Sublime Text, making it easy to install all the other tools you'll need.

  1. Open Sublime Text.

  2. Open the Console by going to View > Show Console or using the shortcut `Ctrl+`` (that's the backtick key, usually to the left of the '1' key).

    Sublime Text 如何配置 Python 开发环境?-图2
    (图片来源网络,侵删)
  3. Copy the appropriate code for your version of Sublime Text and paste it into the console.

    • For Sublime Text 3:

      import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e624c2' + 'e3c43093609bb4de47b918da365acd84'; 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:

      import urllib.request,os,hashlib; h = '6f4c264a24d9b5cc7a63f53ab8be5f4b' + 'bc51ef4ee67f411e3e9be3fa6651d492'; 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)
  4. Press Enter. A new "Package Control" menu will appear in the top menu bar after a few seconds. Restart Sublime Text.

    Sublime Text 如何配置 Python 开发环境?-图3
    (图片来源网络,侵删)

Part 2: Essential Python Packages (via Package Control)

Now that you have Package Control, you can install the packages that make Sublime Text a true Python IDE.

  1. Open the Command Palette by pressing Ctrl+Shift+P.
  2. Type Install Package and select it.
  3. Type the name of the package you want to install and press Enter.

Here are the must-have packages:

Package Name What It Does Why You Need It
Anaconda The core Python package. It provides autocompletion, linting, code formatting, and a powerful Python interpreter. This is the single most important package for Python development in Sublime. It brings IDE-like features to Sublime.
SublimeLinter A framework for "linters" that analyze your code for errors, style issues, and potential bugs. It provides a real-time "code health" check, helping you catch mistakes as you type.
SublimeLinter-flake8 A linter that checks your code against the PEP 8 style guide. Ensures your Python code is clean, readable, and follows community standards.
SublimeLinter-pylint A more powerful and stricter linter that can find more complex bugs. A great complement to flake8 for higher code quality.
GitGutter Shows git diff markers in the gutter of your editor. See exactly which lines have been added, modified, or deleted without leaving your editor.
Theme - Spacegray 4 A popular, beautiful, and highly customizable theme. Makes coding more pleasant and easier on the eyes.

Part 3: Configuration and Workflow

Configure Anaconda

Anaconda works best with a little configuration.

  1. Go to Preferences > Package Settings > Anaconda > Settings - User.

  2. This will open a user settings file. You can override default settings here. A good starting configuration is:

    {
        // Use the system's default Python interpreter
        "python_interpreter": "/usr/bin/python3", // <-- IMPORTANT: Change this to your Python path!
        // Use PEP8 style for code completion and linting
        "anaconda_linter_pep8": true,
        "anaconda_linter_pylint": true,
        // Show pop-up with documentation
        "anaconda_doc_popup_style": "documentation",
        // Format code on save (requires yapf or autopep8)
        "auto_formatting": true,
        "formatting": "yapf" // or "autopep8"
    }

How to find your Python interpreter path:

  • Windows: Open Command Prompt and type where python. Copy the path.
  • macOS/Linux: Open Terminal and type which python3. Copy the path.

Configure SublimeLinter

  1. Go to Preferences > Package Settings > SublimeLinter > Settings - User.

  2. You can enable or disable linters. For example, to use flake8 and pylint:

    {
        "linters": {
            "flake8": {
                "args": ["--max-line-length=120"], // Customize PEP8 rules
                "disable": false
            },
            "pylint": {
                "disable": false
            }
        }
    }

The Build System: How to Run Your Code

By default, Sublime Text can run Python files, but it's better to create a dedicated build system.

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

  2. A new file will open. Replace its contents with this:

    {
        "cmd": ["python", "-u", "$file"],
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "selector": "source.python",
        "env": {"PYTHONIOENCODING": "utf8"}
    }
    • "cmd": This tells Sublime to run the python command on the current file ($file).
    • "file_regex": This helps Sublime parse error messages and jump to the correct line.
    • "selector": This ensures this build system is only used for Python files.
  3. Save the file. Give it a name like Python.sublime-build and save it in the default location that Sublime suggests (usually in a Packages/User folder).

Now, you can run your Python code by:

  • Pressing Ctrl+B.
  • Or, going to Tools > Build System > Python.

The output will appear in a new "output" pane at the bottom of the screen.


Part 4: A Typical Workflow

  1. Create/Open a Python File: File > New File and save it as my_script.py.
  2. Write Code: As you type, you'll see autocompletion pop-ups from Anaconda.
  3. See Linting: If you have a syntax error or a style violation, a red or yellow underline will appear. Hover over it to see the error message.
  4. Run the Script: Press Ctrl+B. Your script will execute, and the output will be shown in the build results pane.
  5. Navigate Code: Place your cursor on a function name and press F12 (or Ctrl+F12) to jump to its definition. Use Ctrl+P to quickly open any file in your project.

Part 5: Debugging in Sublime Text

Sublime Text's debugger isn't as full-featured as in PyCharm or VS Code, but it's functional. It relies on the pdb (Python Debugger) module.

  1. Add a breakpoint: In your Python script, where you want to pause execution, add this line:
    import pdb; pdb.set_trace()
  2. Run the script: Press Ctrl+B to run the script.
  3. Debugging Console: The execution will stop at your breakpoint, and a new console will appear at the bottom. You can now type debugger commands:
    • 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 source code around the current line.
    • p <variable_name> (print): Print the value of a variable.
    • q (quit): Quit the debugger.

Alternatives to Consider

While Sublime Text is excellent, it's good to know what else is out there.

Editor Pros Cons Best For
PyCharm The gold standard for Python. Incredible debugger, built-in testing framework, database tools, web dev support. Can be slow and resource-intensive. The free "Community Edition" is limited. Serious, full-stack Python development, large projects, and those who want an all-in-one solution.
VS Code Free, open-source, and has become a top contender. Excellent Python support (via the official Microsoft extension), great debugger, integrated terminal, and a massive extension marketplace. Can feel heavier than Sublime. The sheer number of options can be overwhelming for beginners. Developers who want a powerful, free, and highly customizable environment that's almost as good as PyCharm.
Jupyter Notebook Interactive coding with visual output (plots, tables, markdown). Perfect for data analysis, machine learning, and education. Not designed for writing large, production-grade applications. Data science, machine learning, interactive exploration, and teaching.

Final Verdict

Sublime Text is an outstanding choice for Python development if you value speed, a minimal interface, and a highly customized workflow. With the right packages, it can be a very powerful and efficient environment. It's particularly well-suited for web development, scripting, and any task where you want a fast and responsive editor.

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