Skip to content

Instantly share code, notes, and snippets.

@n8henrie
Forked from dabrahams/trash
Last active December 16, 2019 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8henrie/30f1bef023da456c42df6467c39bfc48 to your computer and use it in GitHub Desktop.
Save n8henrie/30f1bef023da456c42df6467c39bfc48 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""Send files to MacOS trash bin via applescript."""
import os
from pathlib import Path
import sys
import subprocess
from typing import Iterable, Union
def trash(paths: Iterable[Union[str, Path]]) -> int:
"""Send paths to trash via applescript."""
cmds = []
for path in paths:
cmds.append(f'the POSIX file "{path}"')
cmd = [
"osascript",
"-e",
f'tell app "Finder" to move {{ {", ".join(cmds)} }} to trash',
]
return subprocess.call(cmd, stdout=subprocess.DEVNULL)
def cli() -> None:
"""Provide basic CLI for trash command."""
if len(sys.argv) > 1:
paths = []
for arg in sys.argv[1:]:
p = Path(arg).expanduser().resolve()
if p.exists():
paths.append(p)
else:
print(
f"{sys.argv[0]}: {arg}: No such file or directory",
file=sys.stderr,
)
returncode = trash(paths)
sys.exit(returncode if len(paths) == len(sys.argv[1:]) else 1)
else:
sys.stderr.write(
"usage: %s file(s)\n"
" move file(s) to Trash\n" % os.path.basename(sys.argv[0])
)
sys.exit(64) # matches what rm does on my system
if __name__ == "__main__":
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment