2008-10-30 157 views
1

干脆把文件~/.Trash/将无法​​正常工作,因为如果一个外部驱动器上的文件操作系统,它将文件移动到主系统驱动..OS X:确定回收站位置给定路径

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

给定文件或文件夹路径,确定垃圾文件夹的正确方法是什么?我想这种语言是非常不相关的,但我打算使用Python

回答

5

或者,如果您使用的是OS X 10.5,则可以使用Scripting Bridge通过Finder删除文件。我已经通过RubyCocoa在Ruby代码here中完成了这项工作。它的要点是:

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

你可以很容易地做到与PyObjC类似的东西。

+0

或者appscript,我怀疑。 – 2008-10-31 10:30:09

2

文件管理器API有一对称为FSMoveObjectToTrashAsync和FSPathMoveObjectToTrashSync的函数。

不知道这是否暴露给Python。

4

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 

相当基础,而且也必须被seperatly完成,特别是检查,如果文件名中的垃圾已经存在(有几件事避免覆盖)和实际移动到垃圾,但它似乎涵盖了大部分的东西(内部,外部和网络驱动器)

更新:我想垃圾在Python脚本文件,所以我重新实现戴夫Dribin的Python解决方案:

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") 
+0

Python重新实现对我来说不起作用,在其上运行trashPath后,这些文件仍然存在。阿什利克拉克提出的解决方案确实奏效。 – 2011-03-05 17:32:51

1

另一位在红宝石:

Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete 

您需要rb-appscript宝石,你可以读到它here

2

在Python,而无需使用脚本桥,你可以这样做:

from AppKit import NSWorkspace, NSWorkspaceRecycleOperation 

source = "path holding files" 
files = ["file1", "file2"] 

ws = NSWorkspace.sharedWorkspace() 
ws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, "", files, None)