OSX:确定给定路径的垃圾箱位置

2024-04-26 03:01:32 发布

您现在位置:Python中文网/ 问答频道 /正文

简单地将文件移动到~/.Trash/将不起作用,就像文件在外部驱动器上一样,它会将文件移动到主系统驱动器。。在

另外,还有其他条件,比如外部驱动器上的文件被移到/Volumes/.Trash/501/(或者当前用户的ID是什么)

给定一个文件或文件夹路径,确定垃圾箱文件夹的正确方法是什么?我想这门语言很不相干,但我打算使用Python


Tags: 文件方法用户路径文件夹语言id系统
3条回答

根据http://www.cocoadev.com/index.pl?MoveToTrash中的代码,我得出以下结论:

def get_trash_path(input_file):
    path, file = os.path.split(input_file)
    if path.startswith("/Volumes/"):
        # /Volumes/driveName/.Trashes/<uid>
        s = path.split(os.path.sep)
        # s[2] is drive name ([0] is empty, [1] is Volumes)
        trash_path = os.path.join("/Volumes", s[2], ".Trashes", str(os.getuid()))
        if not os.path.isdir(trash_path):
            raise IOError("Volume appears to be a network drive (%s could not be found)" % (trash_path))
    else:
        trash_path = os.path.join(os.getenv("HOME"), ".Trash")
    return trash_path

相当基本,有一些事情必须分开做,特别是检查文件名是否已经存在于垃圾箱中(以避免覆盖)和实际移动到垃圾箱,但它似乎涵盖了大多数事情(内部、外部和网络驱动器)

更新:我想在Python脚本中丢弃一个文件,所以我在Python中重新实现了Dave Dribin的解决方案:

^{pr2}$

用法很简单:

trashPath("/tmp/examplefile")

更好的方法是NSWorkspaceRecycleOperation,这是可以与-[NSWorkspace performFileOperation:source:destination:files:tag:]一起使用的操作之一。常量的名称是cococoa下一个遗产的另一个产物;它的功能是将项目移到垃圾桶中。在

因为它是Cocoa的一部分,所以Python和Ruby都应该可以使用它。在

或者,如果您在OSX10.5上,您可以使用脚本桥来通过Finder删除文件。我已经通过rubycoa用Ruby代码here完成了这项工作。其要点是:

url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete

你可以很容易地用PyObjC做类似的事情。在

相关问题 更多 >