Python實現(xiàn)自動記錄復(fù)制的文本并保存
前言
先跟大家嘮個事。那天我一邊喝豆?jié){一邊刷知乎,看到一段賊棒的代碼,想著“嗯不錯”,就 Ctrl+C 復(fù)制了一下。結(jié)果剛準(zhǔn)備存進我的代碼片段收藏夾,微信群里彈出消息,我回了個表情包……再一復(fù)制,“啪”一下,原來的內(nèi)容沒了。
我當(dāng)時嘴角抽了一下,感覺就像是打麻將摸到好牌,結(jié)果被人杠了……
于是,我決定寫一個 Python 小工具,專門干這件事:記錄你復(fù)制的文本內(nèi)容,自動保存,再也不怕搞丟靈感或者代碼段!
這玩意我給它起了個有點中二的名字——靈犀剪貼,嘿嘿。

這個工具能干嘛
說人話就是:
- 它會實時監(jiān)控你的剪貼板,偷看你復(fù)制了啥
- 然后它會把你復(fù)制的內(nèi)容保存起來
- 所有文本內(nèi)容會按時間存在一個
.txt文件里,井井有條 - 它不會把你剪貼板復(fù)制的內(nèi)容上傳到網(wǎng)上,所以安全
我們要用到哪些庫
pyperclip:訪問剪貼板;datetime:給你的筆記打上時間戳。
安裝方法也超簡單,來一發(fā)
pip install pyperclip
核心功能
其實最核心的功能:復(fù)制就保存!
這里用輪詢方式,每隔 1 秒檢查一次內(nèi)容,會略微多占一點 CPU(不過 1 秒輪詢其實很輕微)
import pyperclip
import time
last_copied = ""
print("靈犀剪貼 正在監(jiān)聽中…")
with open("copied_texts.txt", "a", encoding="utf-8") as f:
while True:
try:
current = pyperclip.paste()
if current != last_copied:
last_copied = current
timestamp = time.strftime("[%Y-%m-%d %H:%M:%S]")
f.write(f"{timestamp} \n{current}\n\n")
print(f"已保存:{current[:30]}...")
time.sleep(1)
except:
print("靈犀剪貼 運行異常")
break
核心功能:pyperclip.paste()獲取剪貼板里的內(nèi)容
代碼升級
接下來給這段代碼做個升級
- 按天分類保存內(nèi)容,比如
copied_texts_2025_04_09.txt - 加個托盤圖標(biāo) + 開關(guān)
接下來就是見證奇跡的時刻:
import pyperclip
import time
import threading
from pystray import Icon, Menu, MenuItem
from PIL import Image
import os
# 全局控制開關(guān)
class ClipboardMonitor:
def __init__(self):
self.running = True
self.listener_thread = None
self.last_copied = ""
self.current_date = time.strftime("%Y_%m_%d")
def start_listening(self, icon=None):
if (self.listener_thread is None) and self.running:
self.listener_thread = threading.Thread(target=self._listen_clipboard)
self.listener_thread.start()
if not self.running:
self.running = True
self.listener_thread = threading.Thread(target=self._listen_clipboard)
self.listener_thread.start()
if icon: icon.notify("剪貼板監(jiān)聽已啟動", "靈犀剪貼")
def stop_listening(self, icon=None):
if self.running:
self.running = False
if icon: icon.notify("剪貼板監(jiān)聽已停止", "靈犀剪貼")
if self.listener_thread and self.listener_thread.is_alive():
self.listener_thread.join()
def _listen_clipboard(self):
while self.running:
try:
current_content = pyperclip.paste()
if current_content != self.last_copied and current_content.strip() != "":
self.last_copied = current_content
# 處理每日文件切換
today = time.strftime("%Y_%m_%d")
if today != self.current_date:
self.current_date = today
self._save_content(current_content)
time.sleep(0.8)
except Exception as e:
print(f"[ERROR] {str(e)}")
self.running = False
def _save_content(self, content):
timestamp = time.strftime("[%Y-%m-%d %H:%M:%S]")
filename = f"copied_texts_{self.current_date}.txt"
try:
with open(filename, "a", encoding="utf-8") as f:
f.write(f"{timestamp}\n{content}\n\n")
preview = content[:50].replace("\n", "→")
print(f"[已保存] {preview}{'...' if len(content)>50 else ''}")
except Exception as e:
print(f"[保存失敗] {str(e)}")
# 托盤圖標(biāo)管理
class TrayManager:
def __init__(self):
self.monitor = ClipboardMonitor()
# self.monitor.start_listening()
self.icon_on = Image.open("icon_on.png") # 監(jiān)聽中圖標(biāo)
self.icon_off = Image.open("icon_off.png") # 暫停圖標(biāo)
self.icon = None
self._create_tray_icon()
def _create_menu(self):
return Menu(
MenuItem(
'監(jiān)聽中',
self.toggle_listen,
checked=lambda item: self.monitor.running
),
MenuItem(
'打開日志目錄',
self.open_log_dir
),
Menu.SEPARATOR,
MenuItem('退出', self.exit_app)
)
def _create_tray_icon(self):
# 生成托盤圖標(biāo)
self.icon = Icon(
"靈犀剪貼",
self.icon_on if self.monitor.running else self.icon_off,
menu=self._create_menu(),
title="靈犀剪貼"
)
def update_icon_image(self):
self.icon.icon = self.icon_on if self.monitor.running else self.icon_off
def update_menu(self):
self.icon.menu = self._create_tray_icon().menu
def toggle_listen(self, item):
if self.monitor.running:
self.monitor.stop_listening(self.icon)
else:
self.monitor.start_listening(self.icon)
self.update_icon_image()
self.icon.menu = self._create_menu()
self.icon.update_menu()
def open_log_dir(self, item):
log_dir = os.getcwd()
os.startfile(log_dir)
def exit_app(self, item):
self.monitor.stop_listening()
self.icon.stop()
print("程序已安全退出")
def run(self):
self.monitor.start_listening()
self.icon.run()
if __name__ == "__main__":
print("=== 靈犀剪貼監(jiān)控程序 ===")
print("日志將保存在程序所在目錄")
print("可通過系統(tǒng)托盤圖標(biāo)控制")
try:
app = TrayManager()
app.run()
except Exception as e:
print(f"! 程序初始化失敗: {str(e)}")
使用提示:
1.你需要在額外安裝2個庫
pip install Pillow pystray
2. 你需要兩張圖標(biāo):
彩色(監(jiān)聽中)圖標(biāo):比如一片小綠葉、耳朵圖標(biāo)、錄音狀態(tài)啥的。 灰色(暫停)圖標(biāo):同一風(fēng)格的灰色版,表示“停止監(jiān)聽”。
運行程序以后可以在系統(tǒng)托盤看到對應(yīng)的程序了。

使用場景
常用場景舉幾個:
- 寫公眾號、論文、報告時,隨手復(fù)制的引用內(nèi)容直接自動歸檔;
- 和朋友聊天時突然冒出一句“金句”,復(fù)制一下自動保留,方便以后做社媒素材;
- 做調(diào)研、整理資料時,不用每次手動 Ctrl+V 存一堆;
- 懶人備忘神器,復(fù)制即記錄,誰還手動記東西啊!
總結(jié)
說實話,這個項目最開始就是我那天被復(fù)制覆蓋了靈感之后,一氣之下寫的。
寫完之后回頭一看,其實很多我們?nèi)粘?ldquo;忽略掉的動作”(比如復(fù)制),只要有點技術(shù)力,就能變得更智能、更貼心。
有時候,一個小工具,解決的不是技術(shù)問題,是你的生活細(xì)節(jié)和思路的延續(xù)。
到此這篇關(guān)于Python實現(xiàn)自動記錄復(fù)制的文本并保存的文章就介紹到這了,更多相關(guān)Python文本復(fù)制記錄與保存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Flask框架運用Axios庫實現(xiàn)前后端交互詳解
Axios 是一個基于promise的HTTP庫,該庫是一個更好的替代ajax向后端發(fā)送數(shù)據(jù)或請求數(shù)據(jù)的前端組件庫。本文通過示例為大家介紹了如何運用Axios庫實現(xiàn)前后端交互,感興趣的可以了解一下2022-12-12
Python?UnicodedecodeError編碼問題解決方法匯總
本文主要介紹了Python?UnicodedecodeError編碼問題解決方法匯總,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
nlp自然語言處理基于SVD的降維優(yōu)化學(xué)習(xí)
這篇文章主要為大家介紹了nlp自然語言處理基于SVD的降維優(yōu)化學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04

