osc52_copy.py
· 1.0 KiB · Python
Raw
#!/usr/bin/env python3
import base64
import sys
def osc52_copy():
"""
讀取 Standard Input 並透過 OSC52 序列傳送到終端機剪貼簿。
不依賴任何第三方套件 (No loguru, Standard Library only)。
"""
try:
# 嘗試讀取 Standard Input
# 如果卡在這邊等待輸入時按 Ctrl+C,就會被下面的 except 接住
content_str = sys.stdin.read()
except KeyboardInterrupt:
# 捕捉 Ctrl+C,安靜離開或印個換行至 stderr
# 寫入 stderr 不會影響 pipe 到 stdout 的資料
sys.stderr.write("\n")
sys.exit(0)
if not content_str:
return
# 轉成 bytes 準備編碼
content_bytes = content_str.encode("utf-8")
# 轉成 Base64
b64_data = base64.b64encode(content_bytes).decode("utf-8")
# 組合 OSC52 序列
# \033]52;c;{內容}\a
payload = f"\033]52;c;{b64_data}\a"
# 寫入 stdout 讓終端機解析
sys.stdout.write(payload)
sys.stdout.flush()
if __name__ == "__main__":
osc52_copy()
| 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() |
| 42 |