杰瑞科技汇

Sublime Mac下Python环境怎么配置?

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:

  1. Prerequisites: Making sure you have Python installed.
  2. Sublime Text Setup: Installing Sublime Text and essential packages.
  3. Writing & Running Code: The core workflow of writing and executing Python scripts.
  4. Advanced Features: Using Sublime Text as a more powerful IDE (linting, debugging, etc.).
  5. 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 + Space to open Spotlight Search.
  • Type Terminal and 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 use python3 in the terminal).

Important Note: On macOS, you should use the python3 command 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.

  1. Open Sublime Text.

  2. Open the Console: Go to the menu View > Show Console.

  3. 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)
  4. Restart Sublime Text. You should now be able to open the Command Palette with Cmd + Shift + P and see "Package Control: Install Package" as an option.

Step 3: Install Essential Python Packages

  1. Open the Command Palette (Cmd + Shift + P).

  2. Type Package Control: Install Package and press Enter.

  3. 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 yapf or autopep8).
      • 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 .py extension (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.

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

  2. 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 the python3 command on the current file ($file). The -u flag 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 the source.python syntax (i.e., .py files).
  3. Save this file with a memorable name, like Python3.sublime-build, in the default location that Sublime Text suggests (usually a Packages/User folder).

  4. Now, to run your script, simply save your Python file (Cmd + S) and then press Cmd + 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 - User and customize the linters you want to use (e.g., Pylint, Flake8).

Interactive Shell with SublimeREPL

  1. Open your Python file.
  2. Open the Command Palette (Cmd + Shift + P).
  3. Type SublimeREPL: Python - RUN current file and press Enter.
  4. 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.

  1. 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))
  2. Run your script using Cmd + B.

  3. 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 python3 executable in the system's PATH.
  • Solution:
    1. Find the full path to your python3 executable by running which python3 in your Terminal. It will likely be /usr/bin/python3 or /opt/homebrew/bin/python3 (if you installed via Homebrew).
    2. Edit your Python3 build system (Packages/User/Python3.sublime-build).
    3. Change the "cmd" line to use the full path:
      "cmd": ["/usr/bin/python3", "-u", "$file"]

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 - User and 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.

    1. Open your project folder in Sublime Text (Project > Open Folder).

    2. Open the Command Palette and run Terminality: Open.

    3. This will open a terminal tab inside Sublime Text, automatically cd'd into your project directory.

    4. 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
    5. With the virtual environment active, run your script with Cmd + B. Sublime Text will now use the python from your myenv directory.

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