2010-08-19 236 views
4

如何從python中的特定文件夾啓動新的Finder窗口(或Explorer on Win)。我正在尋找的行爲相當於iTunes中的曲目上下文菜單中的「顯示在finder中」鏈接,或者大多數其他程序都會想到它。Python「show in finder」

我目前使用的是使用PyQt構建的UI,我想添加一個菜單選項,如「show log folder」或類似的東西,這會彈出一個新的查找器窗口。

UPDATE:

katrielalex建議嘗試subprocess.Popen("/System/Library/CoreServices/Finder.app")拋出和OSError: Permission denied。試圖通過雙擊啓動Finder.app,表示它已被OS X使用並且無法打開。

當然,必須有辦法打開一個新的Finder窗口。

回答

10

對於OS X,你可以通過py-appscript使用Finder的蘋果事件(的AppleScript)接口:

>>> 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將使用新的-R(Reveal)選項至open命令(請參閱man 1 open):

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

太棒了,謝謝 – 2010-08-19 10:28:50

+0

你也可以掏空'osascript -e「告訴應用程序\」Finder \「以顯示'/ file/to/show'」'...雖然獲得正確的引號可能會很棘手...... – kindall 2013-09-30 19:53:20

1

的Windows:

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

我認爲'explorer'是進程的名稱,是什麼'i:' – 2010-08-19 09:50:20

+0

@Matti:文件夾的路徑。所以如果你想打開'c:\ documents and settings \ foo \ bar',你可以使用'r'explorer'c:\ documents and settings \ foo \ bar'「'。 – katrielalex 2010-08-19 09:52:05

-1

用於取景shell命令

open ~/ 

將打開一個新窗口。

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