-
-
Save n8henrie/30f1bef023da456c42df6467c39bfc48 to your computer and use it in GitHub Desktop.
Script that sends files to trash on MacOS, based on https://apple.stackexchange.com/a/162354/25276 and https://gist.github.com/anthonyjsmith/e0d482bc3fe8ef9e0eb698757efc7624
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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