Python“显示在查找器中”

14

如何在特定文件夹内使用Python打开新的Finder窗口(或Win中的Explorer)。我想要的行为等同于iTunes上跟踪上下文菜单中的“在查找器中显示”链接,或者其他大多数程序。

目前我有一个使用PyQt构建的用户界面,我想添加一个类似于“显示日志文件夹”或类似内容的菜单选项,它会弹出一个新的finder窗口。

更新:

katrielalex的建议中尝试subprocess.Popen("/System/Library/CoreServices/Finder.app") 抛出了OSError: Permission denied。双击Finder.app尝试启动它会提示它正在被OS X使用并且不能打开。

肯定有一种方法可以打开新的Finder窗口。

5个回答

26

对于OS X操作系统,您可以使用Finder的Apple Events(AppleScript)接口,通过py-appscript实现:

>>> from appscript import *
>>> file_to_show = "/Applications/iTunes.app"
>>> app("Finder").reveal(mactypes.Alias(file_to_show).alias)
app(u'/System/Library/CoreServices/Finder.app').startup_disk.folders[u'Applications'].application_files[u'iTunes.app']
>>> #  Finder window of "Applications" folder appears with iTunes selected

编辑:

在OS X 10.6上一个更简单的解决方案是使用open命令的新选项-R(查看)(参见man 1 open):

>>> import subprocess
>>> file_to_show = "/Applications/iTunes.app"
>>> subprocess.call(["open", "-R", file_to_show])

你也可以使用外壳程序,例如 osascript -e "tell application \"Finder\" to reveal '/file/to/show'" ... 不过引号的使用可能会有些棘手... - kindall

3
from subprocess import call
targetDirectory = "~/Desktop"
call(["open", targetDirectory])

当我作为模块运行时,我遇到了错误:call(["open",targetDirectory])) ^ 语法错误:无效的语法 - chikitin

1

Windows:

>>> import subprocess
>>> subprocess.Popen( "explorer i:" )
<subprocess.Popen object at 0x00C46DB0>

我理解explorer是进程的名称,那么i:是什么? - Matti Lyra
@Matti: 文件夹的路径。所以,如果你想打开 c:\documents and settings\foo\bar,你可以使用 r"explorer 'c:\documents and settings\foo\bar'" - Katriel

0
发现了一个很棒的库,名为show-in-file-manager。[GitHub]
所以,对于这个简单的任务,步骤如下:
from showinfm import show_in_file_manager
show_in_file_manager("D:\Program Files (x86)\Steam\logs")

-1

对于Finder来说,这是一个shell命令

open ~/

会打开一个新窗口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接