Fix decode-error

This commit is contained in:
Trung Dinh 2025-05-06 13:02:37 +07:00
parent 8159cbf7d3
commit 2ef26582dd

View file

@ -18,12 +18,16 @@ class ClipboardWatcher:
def start(self):
"""Start watching clipboard for changes"""
self.stop_event = threading.Event()
self.last_clipboard = pyperclip.paste()
# guard against non-UTF8 bytes in the clipboard
try:
self.last_clipboard = pyperclip.paste()
except UnicodeDecodeError:
self.last_clipboard = ""
def watch_clipboard():
while not self.stop_event.is_set():
try:
current = pyperclip.paste()
current = self._safe_paste()
if current != self.last_clipboard:
self.last_clipboard = current
self.io.interrupt_input()
@ -51,6 +55,23 @@ class ClipboardWatcher:
self.watcher_thread = None
self.stop_event = None
def _safe_paste(self) -> str:
"""
Attempt a normal pyperclip.paste(); if it raises a UnicodeDecodeError
fall back to a raw xclip call and replace invalid bytes.
"""
try:
return pyperclip.paste()
except UnicodeDecodeError:
# linux fallback via xclip
import subprocess, shlex
try:
raw = subprocess.check_output(shlex.split("xclip -selection clipboard -o"))
# replace any invalid bytes with <20>
return raw.decode("utf-8", errors="replace")
except Exception:
return ""
def main():
"""Example usage of the clipboard watcher"""