Optimize imports, use tempdir

This commit is contained in:
oitsjustjose 2025-06-08 21:07:09 -05:00
commit 3e853ac1bd

View file

@ -1,21 +1,21 @@
import platform
import subprocess
from argparse import ArgumentParser from argparse import ArgumentParser
from os import unlink from os import unlink
from pathlib import Path from platform import release, system
from random import randint from random import randint
from subprocess import check_call
from tempfile import mktemp
from uuid import uuid4 from uuid import uuid4
def copy_to_clipboard(val: str) -> bool: def copy_to_clipboard(val: str) -> bool:
sys = platform.system() sys = system()
copy_cmd = "" copy_cmd = ""
if sys == "Windows": if sys == "Windows":
copy_cmd = "clip.exe" copy_cmd = "clip.exe"
elif sys == "macOS": elif sys == "macOS":
copy_cmd = "pbcopy" copy_cmd = "pbcopy"
elif sys == "Linux": elif sys == "Linux":
if "WSL" in platform.release(): if "WSL" in release():
copy_cmd = "clip.exe" # Windows native clip.exe still works in WSL copy_cmd = "clip.exe" # Windows native clip.exe still works in WSL
else: else:
copy_cmd = "xclip -selection clipboard" copy_cmd = "xclip -selection clipboard"
@ -23,12 +23,12 @@ def copy_to_clipboard(val: str) -> bool:
print(f"System {sys} is not supported - cannot copy to clipboard") print(f"System {sys} is not supported - cannot copy to clipboard")
return False return False
tmp_path = Path(__file__).joinpath("..").resolve().joinpath(str(uuid4())) tmp_path = mktemp()
with open(tmp_path, "w", encoding="utf-8") as fh: with open(tmp_path, "w", encoding="utf-8") as fh:
fh.write(val.strip()) fh.write(val.strip())
try: try:
ret_val = subprocess.check_call(f"cat {str(tmp_path)} | {copy_cmd}", shell=True) ret_val = check_call(f"cat {str(tmp_path)} | {copy_cmd}", shell=True)
finally: finally:
unlink(tmp_path) unlink(tmp_path)