OS X:确定给定路径的废纸篓位置
简单地把文件移动到 ~/.Trash/
是不行的,因为如果文件在外部硬盘上,它会把文件移动到主系统硬盘上。
还有其他情况,比如外部硬盘上的文件会被移动到 /Volumes/.Trash/501/
(或者是当前用户的ID对应的文件夹)
给定一个文件或文件夹的路径,怎么才能正确找到垃圾桶文件夹呢?我觉得用什么编程语言都无所谓,但我打算用Python。
6 个回答
3
一个更好的方法是 NSWorkspaceRecycleOperation,这是你可以用来进行文件操作的一种方式,具体是通过 -[NSWorkspace performFileOperation:source:destination:files:tag:] 这个方法。这个常量的名字是Cocoa从NeXT继承下来的一个特征,它的作用是把文件移动到垃圾桶。
因为它是Cocoa的一部分,所以在Python和Ruby中都可以使用。
6
根据来自 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的解决方案:
from AppKit import NSURL
from ScriptingBridge import SBApplication
def trashPath(path):
"""Trashes a path using the Finder, via OS X's Scripting Bridge.
"""
targetfile = NSURL.fileURLWithPath_(path)
finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
items = finder.items().objectAtLocation_(targetfile)
items.delete()
使用起来很简单:
trashPath("/tmp/examplefile")
5
另外,如果你使用的是 OS X 10.5,你可以通过 Scripting Bridge 来通过 Finder 删除文件。我在 Ruby 代码中做过这个,具体的代码可以在这里找到,使用的是 RubyCocoa。简单来说就是:
url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete
你也可以用 PyObjC 做类似的事情。