萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Notepad++ 安裝 Python 腳本外掛完整圖文教學

前言

Notepad++ 本身不內建 Python 執行環境,但可透過 **Python Script** 外掛,在編輯器內直接執行 Python 程式碼、操控編輯器物件 (Scintilla API)、自動化文字處理。

安裝步驟 (圖文流程)

1. 開啟外掛管理器

  • 選單列:**外掛 (Plugins) → 外掛管理 (Plugin Manager) / Plugins Admin** (Notepad++ 7.6+ 內建)
  • 若為舊版無 Plugin Manager,請先更新 Notepad++ 至最新版。

2. 搜尋並安裝 Python Script

  1. 在搜尋框輸入 Python Script
  2. 勾選 **Python Script** (作者: Dave Brotherstone)
  3. 點擊 **Install** 安裝
  4. 安裝完成後,**必須重啟 Notepad++** 使外掛生效

3. 驗證安裝與開啟主控台

  • 重啟後,選單列會出現 **Python Script** 選單
  • 點選 **Python Script → Show Console** (或 Ctrl+Alt+Shift+C) 開啟主控台
  • 主控台顯示 >>> 提示符即表示 Python 環境就緒

基本操作與常用 API

執行當前檔案

  • 選單:**Python Script → Run Last Script** 或 Ctrl+Alt+Shift+R
  • 或在主控台輸入:exec(open(notepad.getCurrentFilename()).read())

常用編輯器操作 API (scintilla/editor/notepad 物件)


# 取得/設定全文內容
text = editor.getText()
editor.setText("新內容")

# 取得選取範圍
start, end = editor.getUserCharSelection()
selected = editor.getTextRange(start, end)

# 取得當前行號 (0-based)
line = editor.lineFromPosition(editor.getCurrentPos())

# 插入文字
editor.insertText(editor.getCurrentPos(), "插入的文字")

# 取得所有行
for i in range(editor.getLineCount()):
    print(editor.getLine(i).rstrip())

# 正則取代全文
import re
editor.rereplace(r'\t', '    ')  # Tab 轉 4 空格

建立使用者腳本 (User Scripts)

  1. 選單:**Python Script → New Script**
  2. 輸入檔名 (如 my_tool.py),儲存在 %APPDATA%\Notepad++\plugins\Config\PythonScript\scripts\
  3. 編寫腳本,存檔
  4. **Python Script → Configuration** → 將腳本加入 **Menu items** 可出現在選單,並可指定快捷鍵

實用範例腳本

範例 1:將選取區域排序 (唯一化)


# sort_unique.py
sel_start, sel_end = editor.getUserCharSelection()
if sel_start != sel_end:
    text = editor.getTextRange(sel_start, sel_end)
    lines = sorted(set(text.splitlines()))
    editor.setSelection(sel_start, sel_end)
    editor.replaceSel('\n'.join(lines))

範例 2:批次為檔案加入版權標頭


# add_header.py
import os
header = "# Copyright 2024 MyCompany\n\n"
for f in notepad.getFiles():
    filename = f[0]
    if filename.endswith('.py'):
        notepad.open(filename)
        editor.beginUndoAction()
        editor.insertText(0, header)
        editor.endUndoAction()
        notepad.save()
notepad.messageBox("完成", "加入標頭")

常見問題排查

問題解決方案
Plugin Manager 找不到 Python Script更新 Notepad++ 至 7.6+ (內建 Plugins Admin) 或手動下載 ZIP 解壓到 plugins 資料夾
主控台顯示 "ImportError: No module named ..."Python Script 內建 Python 2.7 (舊版) 或 3.x (新版),需確認版本;第三方套件需放入 scripts 資料夾或 sys.path
腳本無法存取檔案系統檢查 Notepad++ 是否以管理員身分執行;檔案路徑含中文需注意編碼
編輯器操作無效果確認在正確視圖 (editor1/editor2);多檔案時用 notepad.activateBufferID 切換

替代方案

  • NppExec:執行外部命令 (如 python "$(FULL_CURRENT_PATH)"),輕量、無 Python API。
  • 外部工具:F5 執行 cmd /k python "$(FULL_CURRENT_PATH)"。
  • VS Code / PyCharm:完整 IDE 體驗,建議正式開發使用。
copyright © 萬盛學電腦網 all rights reserved