本文目录导读:

- 跨平台:Python + pyperclip
- macOS:AppleScript快速清理
- Windows:PowerShell脚本
- Linux:Bash + xclip/xsel
- 自动脚本:跨平台自动整理
- 系统级集成(自动化工具)
- 使用建议
Python + pyperclip
功能:增强剪贴板操作(如获取、设置、监控变化)
import pyperclip
import time
from plyer import notification
# 初始化安装:pip install pyperclip plyer
# 1. 基础复制/粘贴
def enhanced_copy():
text = pyperclip.paste()
# 自动格式化(去除多余空格)
cleaned = ' '.join(text.split())
pyperclip.copy(cleaned)
print(f"已格式化复制: {cleaned[:50]}...")
# 2. 剪贴板历史监控
class ClipboardMonitor:
def __init__(self, max_history=20):
self.history = []
self.max_history = max_history
def start_monitoring(self):
last_text = ""
while True:
current = pyperclip.paste()
if current != last_text and current.strip():
self.history.append(current)
if len(self.history) > self.max_history:
self.history.pop(0)
notification.notify(
title="剪贴板已更新",
message=current[:100],
timeout=2
)
last_text = current
time.sleep(1)
# 运行
if __name__ == "__main__":
monitor = ClipboardMonitor()
monitor.start_monitoring()
macOS:AppleScript快速清理
功能:一键清空剪贴板或格式化内容
-- 清空剪贴板
on clear_clipboard()
set the clipboard to ""
display notification "剪贴板已清空" with title "Clean Clipboard"
end clear_clipboard
-- 将纯文本内容转为无格式文本
on convert_to_plain_text()
set oldText to (the clipboard as text)
set the clipboard to oldText as string
end convert_to_plain_text
-- 可绑定快捷键(通过Automator或第三方工具调用)
Windows:PowerShell脚本
功能:管理剪贴板历史、批量操作
# 查看当前剪贴板内容类型
function Get-ClipboardInfo {
$data = [System.Windows.Forms.Clipboard]::GetDataObject()
$formats = $data.GetFormats()
Write-Host "剪贴板包含以下格式:"
$formats | ForEach-Object { Write-Host " - $_" }
}
# 批量复制多个文件路径
function Copy-FilePaths {
param(
[string[]]$Paths
)
$joined = $Paths -join "`n"
Set-Clipboard -Value $joined
Write-Host "已复制 $($Paths.Length) 个路径到剪贴板"
}
# 监控剪贴板变化(需管理员权限)
function Watch-Clipboard {
param([int]$Interval=1)
$last = Get-Clipboard
while ($true) {
Start-Sleep -Seconds $Interval
$current = Get-Clipboard
if ($current -ne $last) {
Write-Host "剪贴板更新: $($current.Substring(0, [Math]::Min(50, $current.Length)))..."
$last = $current
}
}
}
# 加载Windows.Forms(首次运行需要)
Add-Type -AssemblyName System.Windows.Forms
Linux:Bash + xclip/xsel
功能:终端中的剪贴板控制
#!/bin/bash
# clipboard_manager.sh
# 复制到剪贴板(带格式)
function clip_copy() {
if command -v xclip &> /dev/null; then
echo "$1" | xclip -selection clipboard
elif command -v xsel &> /dev/null; then
echo "$1" | xsel --clipboard --input
fi
echo "已复制: ${1:0:50}..."
}
# 获取剪贴板内容并处理
function clip_process() {
local content
if command -v xclip &> /dev/null; then
content=$(xclip -selection clipboard -o)
else
content=$(xsel --clipboard --output)
fi
# 转为大写
clip_copy "${content^^}"
echo "已转换并复制: ${content:0:50} -> ${content^^:0:50}..."
}
# 批量处理多个文本
function batch_clip() {
while IFS= read -r line; do
clip_copy "$line"
sleep 0.5
done < "$1"
}
# 使用示例
case "$1" in
copy) clip_copy "$2" ;;
process) clip_process ;;
batch) batch_clip "$2" ;;
watch) watch -n 1 "xclip -selection clipboard -o 2>/dev/null || echo '空'" ;;
*) echo "用法: ./clipboard.sh {copy|process|batch|watch} [参数]" ;;
esac
自动脚本:跨平台自动整理
功能:智能合并、去重、格式化
# auto_clipboard.py
import pyperclip
import re
from datetime import datetime
class SmartClipboard:
@staticmethod
def auto_format():
"""自动检测并优化剪贴板内容"""
text = pyperclip.paste()
# 1. 去除多余空白
text = re.sub(r'\s+', ' ', text).strip()
# 2. 处理URL(自动添加协议)
if text.startswith('www.'):
text = 'https://' + text
# 3. 处理邮件地址(转为小写)
if '@' in text and '.' in text:
text = text.lower()
# 4. 添加时间戳
timestamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
pyperclip.copy(f"{timestamp} {text}")
print("智能格式化完成")
@staticmethod
def merge_lines():
"""将多行合并为一行(用逗号分隔)"""
text = pyperclip.paste()
lines = [line.strip() for line in text.split('\n') if line.strip()]
merged = ', '.join(lines)
pyperclip.copy(merged)
print(f"已合并 {len(lines)} 行")
# 运行
if __name__ == "__main__":
sc = SmartClipboard()
sc.auto_format()
系统级集成(自动化工具)
AutoHotkey (Windows) 脚本示例:
; win+shift+v 打开剪贴板历史
#+v::
Send, ^v
Sleep, 50
Send, !{PrintScreen} ; 调用win10内置剪贴板历史
return
; ctrl+alt+c 复制并转为小写
^!c::
Clipboard := ""
Send, ^c
ClipWait, 1
Clipboard := Format("{:L}", Clipboard) ; 转为小写
ToolTip, 已转为小写: %Clipboard%
SetTimer, RemoveToolTip, -2000
return
RemoveToolTip:
ToolTip
return
使用建议
- 日常使用:推荐跨平台的
pyperclip+ 历史监控脚本 - 专业场景:Mac用户可用
Alfred或Hazel,Windows用Ditto或ClipX - 开发者:搭配IDE剪贴板增强插件(如VS Code的
Clipboard Manager) - 安全场景:自动清空敏感信息,定时清除历史记录
选择脚本时,请先评估你的操作系统和需求复杂度,对于简单操作,系统自带的剪贴板功能(Win+V历史记录、macOS通用剪贴板)已足够;需要更强大功能时再定制脚本。