timmy a révisé ce gist 23 hours ago. Aller à la révision
1 file changed, 41 insertions
osc52_copy.py(fichier créé)
| @@ -0,0 +1,41 @@ | |||
| 1 | + | #!/usr/bin/env python3 | |
| 2 | + | import base64 | |
| 3 | + | import sys | |
| 4 | + | ||
| 5 | + | ||
| 6 | + | def osc52_copy(): | |
| 7 | + | """ | |
| 8 | + | 讀取 Standard Input 並透過 OSC52 序列傳送到終端機剪貼簿。 | |
| 9 | + | 不依賴任何第三方套件 (No loguru, Standard Library only)。 | |
| 10 | + | """ | |
| 11 | + | try: | |
| 12 | + | # 嘗試讀取 Standard Input | |
| 13 | + | # 如果卡在這邊等待輸入時按 Ctrl+C,就會被下面的 except 接住 | |
| 14 | + | content_str = sys.stdin.read() | |
| 15 | + | ||
| 16 | + | except KeyboardInterrupt: | |
| 17 | + | # 捕捉 Ctrl+C,安靜離開或印個換行至 stderr | |
| 18 | + | # 寫入 stderr 不會影響 pipe 到 stdout 的資料 | |
| 19 | + | sys.stderr.write("\n") | |
| 20 | + | sys.exit(0) | |
| 21 | + | ||
| 22 | + | if not content_str: | |
| 23 | + | return | |
| 24 | + | ||
| 25 | + | # 轉成 bytes 準備編碼 | |
| 26 | + | content_bytes = content_str.encode("utf-8") | |
| 27 | + | ||
| 28 | + | # 轉成 Base64 | |
| 29 | + | b64_data = base64.b64encode(content_bytes).decode("utf-8") | |
| 30 | + | ||
| 31 | + | # 組合 OSC52 序列 | |
| 32 | + | # \033]52;c;{內容}\a | |
| 33 | + | payload = f"\033]52;c;{b64_data}\a" | |
| 34 | + | ||
| 35 | + | # 寫入 stdout 讓終端機解析 | |
| 36 | + | sys.stdout.write(payload) | |
| 37 | + | sys.stdout.flush() | |
| 38 | + | ||
| 39 | + | ||
| 40 | + | if __name__ == "__main__": | |
| 41 | + | osc52_copy() | |
Plus récent
Plus ancien