Notepad++ 本身不內建 Python 執行環境,但可透過 **Python Script** 外掛,在編輯器內直接執行 Python 程式碼、操控編輯器物件 (Scintilla API)、自動化文字處理。
Python ScriptCtrl+Alt+Shift+C) 開啟主控台>>> 提示符即表示 Python 環境就緒Ctrl+Alt+Shift+Rexec(open(notepad.getCurrentFilename()).read())
# 取得/設定全文內容
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 空格
my_tool.py),儲存在 %APPDATA%\Notepad++\plugins\Config\PythonScript\scripts\
# 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))
# 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 切換 |
python "$(FULL_CURRENT_PATH)"),輕量、無 Python API。F5 執行 cmd /k python "$(FULL_CURRENT_PATH)"。