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

這個(gè)工具能干嘛
說(shuō)人話(huà)就是:
- 它會(huì)實(shí)時(shí)監(jiān)控你的剪貼板,偷看你復(fù)制了啥
- 然后它會(huì)把你復(fù)制的內(nèi)容保存起來(lái)
- 所有文本內(nèi)容會(huì)按時(shí)間存在一個(gè)
.txt文件里,井井有條 - 它不會(huì)把你剪貼板復(fù)制的內(nèi)容上傳到網(wǎng)上,所以安全
我們要用到哪些庫(kù)
pyperclip:訪問(wèn)剪貼板;datetime:給你的筆記打上時(shí)間戳。
安裝方法也超簡(jiǎn)單,來(lái)一發(fā)
pip install pyperclip
核心功能
其實(shí)最核心的功能:復(fù)制就保存!
這里用輪詢(xún)方式,每隔 1 秒檢查一次內(nèi)容,會(huì)略微多占一點(diǎn) CPU(不過(guò) 1 秒輪詢(xún)其實(shí)很輕微)
import pyperclip
import time
last_copied = ""
print("靈犀剪貼 正在監(jiān)聽(tīng)中…")
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("靈犀剪貼 運(yùn)行異常")
break
核心功能:pyperclip.paste()獲取剪貼板里的內(nèi)容
代碼升級(jí)
接下來(lái)給這段代碼做個(gè)升級(jí)
- 按天分類(lèi)保存內(nèi)容,比如
copied_texts_2025_04_09.txt - 加個(gè)托盤(pán)圖標(biāo) + 開(kāi)關(guān)
接下來(lái)就是見(jiàn)證奇跡的時(shí)刻:
import pyperclip
import time
import threading
from pystray import Icon, Menu, MenuItem
from PIL import Image
import os
# 全局控制開(kāi)關(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)聽(tīng)已啟動(dòng)", "靈犀剪貼")
def stop_listening(self, icon=None):
if self.running:
self.running = False
if icon: icon.notify("剪貼板監(jiān)聽(tīng)已停止", "靈犀剪貼")
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)}")
# 托盤(pán)圖標(biāo)管理
class TrayManager:
def __init__(self):
self.monitor = ClipboardMonitor()
# self.monitor.start_listening()
self.icon_on = Image.open("icon_on.png") # 監(jiān)聽(tīng)中圖標(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)聽(tīng)中',
self.toggle_listen,
checked=lambda item: self.monitor.running
),
MenuItem(
'打開(kāi)日志目錄',
self.open_log_dir
),
Menu.SEPARATOR,
MenuItem('退出', self.exit_app)
)
def _create_tray_icon(self):
# 生成托盤(pán)圖標(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("可通過(guò)系統(tǒng)托盤(pán)圖標(biāo)控制")
try:
app = TrayManager()
app.run()
except Exception as e:
print(f"! 程序初始化失敗: {str(e)}")
使用提示:
1.你需要在額外安裝2個(gè)庫(kù)
pip install Pillow pystray
2. 你需要兩張圖標(biāo):
彩色(監(jiān)聽(tīng)中)圖標(biāo):比如一片小綠葉、耳朵圖標(biāo)、錄音狀態(tài)啥的。 灰色(暫停)圖標(biāo):同一風(fēng)格的灰色版,表示“停止監(jiān)聽(tīng)”。
運(yùn)行程序以后可以在系統(tǒng)托盤(pán)看到對(duì)應(yīng)的程序了。

使用場(chǎng)景
常用場(chǎng)景舉幾個(gè):
- 寫(xiě)公眾號(hào)、論文、報(bào)告時(shí),隨手復(fù)制的引用內(nèi)容直接自動(dòng)歸檔;
- 和朋友聊天時(shí)突然冒出一句“金句”,復(fù)制一下自動(dòng)保留,方便以后做社媒素材;
- 做調(diào)研、整理資料時(shí),不用每次手動(dòng) Ctrl+V 存一堆;
- 懶人備忘神器,復(fù)制即記錄,誰(shuí)還手動(dòng)記東西?。?/li>
總結(jié)
說(shuō)實(shí)話(huà),這個(gè)項(xiàng)目最開(kāi)始就是我那天被復(fù)制覆蓋了靈感之后,一氣之下寫(xiě)的。
寫(xiě)完之后回頭一看,其實(shí)很多我們?nèi)粘?ldquo;忽略掉的動(dòng)作”(比如復(fù)制),只要有點(diǎn)技術(shù)力,就能變得更智能、更貼心。
有時(shí)候,一個(gè)小工具,解決的不是技術(shù)問(wèn)題,是你的生活細(xì)節(jié)和思路的延續(xù)。
到此這篇關(guān)于Python實(shí)現(xiàn)自動(dòng)記錄復(fù)制的文本并保存的文章就介紹到這了,更多相關(guān)Python文本復(fù)制記錄與保存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3如何日志同時(shí)輸出到控制臺(tái)和文件
這篇文章主要介紹了Python3如何日志同時(shí)輸出到控制臺(tái)和文件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
基于Python對(duì)xsl&xslx文件進(jìn)行操作
這篇文章主要為大家詳細(xì)介紹了如何使用Python對(duì)xsl&xslx文件進(jìn)行一些基本操作,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-12-12
Python實(shí)現(xiàn)視頻mp4垂直和水平拼接
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)視頻mp4垂直和水平拼接功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-02-02
Python應(yīng)用利器之緩存機(jī)制的妙用詳解
在 Python 應(yīng)用程序中,使用緩存能夠顯著提高性能并降低資源消耗,本文將詳細(xì)介紹如何在 Python 中實(shí)現(xiàn)緩存機(jī)制,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
Python2手動(dòng)安裝更新pip過(guò)程實(shí)例解析
這篇文章主要介紹了Python2手動(dòng)安裝更新pip過(guò)程實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
在Python程序中操作文件之isatty()方法的使用教程
這篇文章主要介紹了在Python程序中操作文件之isatty()方法的使用教程,是Python入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-05-05
Python利用omegaconf庫(kù)輕松實(shí)現(xiàn)配置文件管理
omegaconf是一個(gè)靈活且強(qiáng)大的Python配置管理庫(kù),支持YAML,dict,列表等多種數(shù)據(jù)格式,下面我們就來(lái)看看如何使用omegaconf實(shí)現(xiàn)配置文件管理吧2025-02-02

