本文目录导读:

获取剪贴板历史比直接读取当前剪贴板要复杂得多,因为操作系统默认不提供标准的剪贴板历史API(直接读取历史记录是安全敏感操作),以下是几种可行的方案,取决于你的操作系统和需求:
Windows 系统(使用 PowerShell)
Windows 10/11 内置了剪贴板历史功能,但需要通过注册表或UI自动化来获取:
# 方法1:直接从注册表读取(需要已启用剪贴板历史)
$historyPath = "HKCU:\Software\Microsoft\Clipboard\History"
if (Test-Path $historyPath) {
Get-ChildItem $historyPath | ForEach-Object {
$_.GetValue("ClipboardData")
}
}
# 方法2:使用 UI Automation(需要安装工具)
# 安装剪贴板管理器后读取其存储文件
$historyFile = "$env:LOCALAPPDATA\Microsoft\Windows\Clipboard\History\*.dat"
# 实际文件是二进制格式,需专用解析器
使用 Python(跨平台,需要额外库)
# 注意:大多数Python库只能读取当前剪贴板,历史需要额外的剪贴板管理器
# 方案A:使用 pyperclip(仅当前剪贴板)
import pyperclip
current = pyperclip.paste()
print(f"当前剪贴板: {current}")
# 方案B:使用 tkinter(仅当前剪贴板)
import tkinter as tk
root = tk.Tk()
root.withdraw()
current = root.clipboard_get()
print(f"当前剪贴板: {current}")
# 方案C:监听并记录历史
import pyperclip
import time
history = []
last = ""
while True:
try:
current = pyperclip.paste()
if current != last:
history.append((time.time(), current))
print(f"新内容: {current[:30]}...")
last = current
time.sleep(1)
except KeyboardInterrupt:
break
macOS 系统
# 读取当前剪贴板 pbpaste # 查看剪贴板历史(需要第三方工具如 Clipy) # 或使用 AppleScript 调用 UI 元素 osascript -e 'tell application "System Events" to get clipboard history'
Linux(X11)
# 使用 xclip 读取当前剪贴板
xclip -o -selection clipboard
# 使用 xsel 读取
xsel --clipboard
# 监听剪贴板变化(需要手动记录)
while true; do
current=$(xclip -o -selection clipboard 2>/dev/null)
sleep 1
done
使用第三方剪贴板管理器脚本
许多剪贴板管理器会以文件形式存储历史:
# 以 Ditto(Windows)为例
import sqlite3
import json
# Ditto 数据库位置
db_path = r"C:\Users\%USERNAME%\AppData\Roaming\Ditto\Ditto.db"
# 或使用环境变量
# db_path = os.path.expandvars(r"%APPDATA%\Ditto\Ditto.db")
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 查询剪贴板历史
cursor.execute("SELECT text FROM Main ORDER BY sequence DESC LIMIT 10")
history = cursor.fetchall()
for item in history:
print(item[0])
conn.close()
重要安全提示
- 权限限制:现代系统(特别是 macOS 和 Linux)限制直接访问剪贴板历史
- 隐私风险:剪贴板可能包含密码、信用卡号等敏感信息
- 替代方案:推荐使用官方支持的方法:
- Windows:Win+V 快捷键查看内置历史
- macOS:使用第三方工具如 Alfred、ClipMenu
- Linux:安装
copyq或clipmenu
最佳实践建议
如果你需要程序化访问剪贴板历史,最好的方法是:
# 1. 使用剪贴板监听器持续记录
# 2. 启动时清空历史
# 3. 只记录文本类型
# 4. 限制历史长度(如最近100条)
class ClipboardTracker:
def __init__(self, max_history=100):
self.history = []
self.max = max_history
self.last = ""
def start_monitoring(self):
import pyperclip
import time
while True:
try:
current = pyperclip.paste()
if current and current != self.last:
self.history.append({
'time': time.time(),
'content': current[:500] # 限制长度
})
if len(self.history) > self.max:
self.history.pop(0)
self.last = current
time.sleep(0.5)
except KeyboardInterrupt:
break
except:
continue
tracker = ClipboardTracker()
# tracker.start_monitoring() # 取消注释运行
没有简单通用的方法直接从系统获取剪贴板历史,最可靠的方式是自己实现监听器记录历史或使用第三方剪贴板工具的API。