Search code examples
macospyobjcscripting-bridge

Restore Trash Item using ScriptingBridge in Mac OS X via PyObjC


I'm trying to figure out a way to restore (Put Back) Trash Item using ScriptingBridge via PyObjC.

There isn't enough documentation here

from AppKit import NSURL
from ScriptingBridge import SBApplication
targetfile = NSURL.fileURLWithPath_(f.realpath)
finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
trash_items = finder.trash.items()

Any suggestions?

Thanks!

PS: I'm using Snow Leopard.


Solution

  • When dealing with AppleScript-able applications from Python, you will almost always find it easier to use appscript rather than Apple's ScriptingBridge or PyObjC. One way to do it:

    from appscript import *
    # move file to trash
    app("Finder").move(mactypes.File(f.realpath),to=its.trash)
    # get names of all items in the Trash
    app("Finder").trash.items.name.get()
    # move file x.txt from Trash to Desktop Folder
    app("Finder").trash.files["x.txt"].move(to=its.desktop)
    

    The trick is getting the right Apple Event reference to the desired files and folders. It may be even easier to cheat a bit and get the path to the trash folder and use standard file system operations on it:

    >>> app("System Events").trash.POSIX_path()
    u'/Users/nad/.Trash'