1. 程式人生 > 程式設計 >python兩種獲取剪貼簿內容的方法

python兩種獲取剪貼簿內容的方法

第一種

import win32clipboard
import time
#速度快 容易出錯
class niubi():
 def lihai(self):
  while True:
   #jianting().main()
   t = jianting().main()
   print(t)

class jianting():
 def clipboard_get(self):
  """獲取剪貼簿資料"""
  win32clipboard.OpenClipboard()
  data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
  win32clipboard.CloseClipboard()
  return data

 def main(self):
  """後臺指令碼:每隔0.2秒,讀取剪下板文字,檢查有無指定字元或字串,如果有則執行替換"""
  # recent_txt 存放最近一次剪下板文字,初始化值只多執行一次paste函式讀取和替換
  recent_txt = self.clipboard_get()
  while True:
   # txt 存放當前剪下板文字
   txt = self.clipboard_get()
   # 剪下板內容和上一次對比如有變動,再進行內容判斷,判斷後如果發現有指定字元在其中的話,再執行替換
   if txt != recent_txt:
    # print(f'txt:{txt}')
    recent_txt = txt # 沒查到要替換的子串,返回None
    return recent_txt

   # 檢測間隔(延遲0.2秒)
   time.sleep(0.2)

if __name__ == '__main__':
 niubi().lihai()

速度快,但很容易出錯, 一般人感覺不出來速度。 不建議使用。

方法二:

import pyperclip
import time

#穩定不出錯
class niubi():
 def lihai(self):
  while True:
   #jianting().main()
   t = jianting().main()
   print(t)
class jianting():
 def clipboard_get(self):
  """獲取剪貼簿資料"""
  data = pyperclip.paste() #主要這裡差別
  return data

 def main(self):
  """後臺指令碼:每隔0.2秒,讀取剪下板文字,檢查有無指定字元或字串,如果有則執行替換"""
  # recent_txt 存放最近一次剪下板文字,初始化值只多執行一次paste函式讀取和替換
  recent_txt = self.clipboard_get()
  while True:
   # txt 存放當前剪下板文字
   txt = self.clipboard_get()
   # 剪下板內容和上一次對比如有變動,再進行內容判斷,判斷後如果發現有指定字元在其中的話,再執行替換
   if txt != recent_txt:
    # print(f'txt:{txt}')
    recent_txt = txt # 沒查到要替換的子串,返回None
    return recent_txt

   # 檢測間隔(延遲0.2秒)
   time.sleep(0.2)

if __name__ == '__main__':
 niubi().lihai()

我一般把第二種 用在程式中。

想要了解更多關於python的知識,資訊,實用工具歡迎關注python客棧

python兩種獲取剪貼簿內容的方法

以上就是python兩種獲取剪貼簿內容的方法的詳細內容,更多關於python 獲取剪貼簿內容的資料請關注我們其它相關文章!