杰瑞科技汇

Emacs Python Mode 怎么配置优化?

Of course! Emacs has a rich and powerful ecosystem for Python development. It's not a single "mode" but rather a combination of built-in and third-party packages that work together to create a fantastic experience.

Here's a comprehensive guide covering the most popular and effective setups.


The Big Picture: Two Main Philosophies

When people talk about Python in Emacs, they're usually referring to one of two main approaches:

  1. The "Classic" LSP Setup: This uses the Language Server Protocol (LSP). A separate server (like pyright or pylsp) does the heavy lifting of code analysis, autocompletion, and refactoring. Emacs acts as a client, sending your code to the server and displaying the results. This is the modern, standard approach and is highly recommended.
  2. The "Built-in" Setup: This relies on Emacs' built-in python mode, which provides basic syntax highlighting and indentation. For more advanced features, you combine it with packages like elpy or conda.el. This setup is simpler to configure but offers fewer features than a full LSP setup.

The Modern & Recommended Setup: LSP with pylsp

This setup gives you professional-grade features like intelligent autocompletion, real-time error checking, go-to-definition, and refactoring.

Core Components:

  • lsp-mode: The Emacs client for the Language Server Protocol.
  • lsp-pyright: An LSP client for pyright, a fast, static type checker and language server for Python. (Alternatively, lsp-pylsp for python-lsp-server).
  • company: The standard autocompletion framework for Emacs.
  • flycheck: A real-time syntax checking and linting framework.

Step-by-Step Configuration

Step 1: Install the Python Language Server

First, you need to install a language server on your system. pyright is an excellent choice.

# Using pip (requires Python 3.7+)
pip install pyright
# Or using npm (requires Node.js)
npm install -g pyright

Step 2: Install Emacs Packages

Use your favorite package manager (like use-package or straight.el).

;; Install use-package if you haven't already
;; (package-install 'use-package)
(use-package python
  ;; Use the built-in python-mode, but enhance it with LSP
  :ensure t
  :hook (python-mode . lsp)
  :config
  (setq lsp-pyright-use-library-text-for-types t))
(use-package lsp-pyright
  :ensure t
  :after python
  :config
  (setq lsp-pyright-diagnostic-mode "workspace")) ; Show workspace errors
(use-package company
  :ensure t
  :hook (python-mode . company-mode)
  :config
  (setq company-idle-delay 0.2))
(use-package flycheck
  :ensure t
  :hook (python-mode . flycheck-mode))

Step 3: Optional but Highly Recommended

  • DREY (Docker, Repl, Explorer, Yasnippet): A beautiful and modern Python development environment that layers on top of LSP.

    • Features: Integrated REPL, file explorer, Docker support, and snippets.
    • Installation:
      (use-package drey
        :ensure t
        :after lsp-mode
        :config
        (drey-setup))
  • Black Formatter: Enforce the Black code style automatically.

    • Installation:
      (pip install black)
    • Emacs Configuration:
      (use-package python-black
        :ensure t
        :after python
        :hook (python-mode . python-black-on-save-mode))

The "All-in-One" Setup: elpy

elpy was the go-to solution for years and is still a great, lightweight option. It bundles many tools into a single package.

Core Components:

  • elpy: The main package that provides an integrated Python development environment.
  • jedi: The backend for autocompletion and navigation (now largely superseded by LSP, but still used by elpy).
  • blacken: For Black formatting.
  • pyvenv: For managing virtual environments.

Step-by-Step Configuration

Step 1: Install Dependencies

;; Install elpy from MELPA
(package-install 'elpy)
;; Initialize elpy
(elpy-enable)

Step 2: Install Python Dependencies

pip install jedi
pip install black  # For formatting
pip install flake8 # For linting (optional)

Step 3: Configure elpy

You might want to tweak some settings for a better experience.

;; Use Jedi for autocompletion (elpy might default to this now)
(setq elpy-modules (delq 'elpy-module-highlight-indentation elpy-modules))
(setq elpy-rpc-python-command "python3") ;; If you have multiple Python versions
;; Use black for formatting
(require 'blacken)
(add-hook 'python-mode-hook 'blacken-mode)
;; Use pyvenv to manage virtual environments
(package-install 'pyvenv)

The Minimalist Built-in Setup

If you prefer a lightweight setup with just the basics, you can use Emacs' built-in python-mode and add a few helpers.

;; Use the built-in python-mode
(add-hook 'python-mode-hook
          (lambda ()
            ;; Enable line numbers and auto-fill mode
            (display-line-numbers-mode)
            (auto-fill-mode 1)
            ;; Use flycheck for linting
            (flycheck-mode 1)
            ;; Use company for autocompletion
            (company-mode 1)))
;; Optional: Use pyvenv for virtual environments
(use-package pyvenv
  :ensure t
  :config
  (pyvenv-mode t))

Essential Commands for Python Development

Here are the most common commands you'll use, regardless of your setup.

Feature Command (M-x...) Keybinding (Common) Description
Run Script python-shell-send-buffer C-c C-c Execute the current Python buffer in a REPL.
Start REPL run-python C-c C-z Open a Python REPL in an *Python* buffer.
Send Region python-shell-send-region C-c C-r Send the currently selected region of code to the REPL.
Send Statement python-shell-send-statement C-c C-s Send the current statement to the REPL.
Go to Definition lsp-find-definition M-. Jump to the definition of the symbol under the cursor. (LSP only)
Find References lsp-find-references M-? Find all references to the symbol under the cursor. (LSP only)
Rename Symbol lsp-rename M-r Rename the symbol under the cursor across the project. (LSP only)
Show Documentation lsp-describe-thing-at-point C-c C-d Show the docstring for the symbol under the cursor. (LSP only)
Format Code python-black-buffer C-c C-f Format the current buffer using Black.
Activate Virtual Env pyvenv-activate Prompt to activate a Python virtual environment.

Summary: Which Setup Should You Choose?

Setup Pros Cons Best For
LSP (pyright) Most powerful features (refactoring, type hints), excellent autocompletion, language-agnostic. Requires installing a server, slightly more complex initial setup. Everyone. This is the modern standard and provides the best experience.
elpy "All-in-one" simplicity, good integration with tools like black, mature and stable. Can feel dated, development has slowed, some features are less advanced than LSP. Users who want a simpler, self-contained package without dealing with separate servers.
Built-in Extremely lightweight, no external dependencies, very fast. Lacks advanced features like refactoring, requires manual setup for linting/formatting. Users on very old systems, those who want absolute minimalism, or beginners learning Emacs basics.

Final Recommendation: Start with the LSP setup. It provides the best balance of power, features, and modern development practices. Once you're comfortable, you can add drey for an even more integrated workflow.

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