[英]Is there a cross-platform way to open a file browser in Python?
我正在考慮與webbrowser模塊類似的東西,但適用於文件瀏覽器。 在 Windows 中,我想打開資源管理器,在 Linux 中的 GNOME 中,我想在 KDE 上打開 nautilus、Konqueror 等。如果可以避免的話,我寧願不把它弄亂。 ;-)
如果我可以避免它,我寧願不把它搞砸。
Weeell我認為你需要一點平台嗅探kludge,但希望不如可怕的命令嗅探webbrowser
模塊。 這是對它的第一次嘗試:
if sys.platform=='win32':
subprocess.Popen(['start', d], shell= True)
elif sys.platform=='darwin':
subprocess.Popen(['open', d])
else:
try:
subprocess.Popen(['xdg-open', d])
except OSError:
# er, think of something else to try
# xdg-open *should* be supported by recent Gnome, KDE, Xfce
請注意,對於文件名中的空格,win32版本當前將失敗。 錯誤2304可能與此有關,但似乎存在參數轉義和Windows shell( cmd /c ...
)的基本問題,因為你不能嵌套雙引號而你不能^ -escape引號或空格。 我還沒有找到任何方法來引用和運行cmd /c start C:\\Documents and Settings
從命令行運行cmd /c start C:\\Documents and Settings
。
ETA re nosklo的評論:僅在Windows上,有一種內置方式可以做到:
if sys.platform=='win32':
os.startfile(d)
這是找到shell並用它打開一個文件夾的不太好的替代解決方案,你現在不需要它,但我會留下來。(部分原因是因為它可能用於別的東西,但主要是因為我花時間打死該死的東西!)
if sys.platform=='win32':
import _winreg
path= r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon')
for root in (_winreg.HKEY_CURRENT_USER, _winreg.HKEY_LOCAL_MACHINE):
try:
with _winreg.OpenKey(root, path) as k:
value, regtype= _winreg.QueryValueEx(k, 'Shell')
except WindowsError:
pass
else:
if regtype in (_winreg.REG_SZ, _winreg.REG_EXPAND_SZ):
shell= value
break
else:
shell= 'Explorer.exe'
subprocess.Popen([shell, d])
剛遇到這篇文章時遇到了類似的問題Choosing a file in Python with simple Dialog 。 我建議去那里查看示例和代碼片段。 基本上提供了2個建議:
我會先嘗試 tkinter,如果失敗,請嘗試其中一種選擇。
由於這個線程很舊,可能值得分享更新的替代方案,這些替代方案可能是最近出現的,供其他人尋找同一問題的答案。
我不知道是否存在一個現成的模塊,但如果有,它應該在Activestate的python cookbok上( http://code.activestate.com/recipes/langs/python/ )
另外,至少在gnome和mac os上,你可以執行“gnome-open http:// blah ”和“open http:// blah ”(在mac上); 兩者都將打開用戶首選瀏覽器中的URL。
對於linux,還要檢查freedesktop.org--一個涵蓋Gnome和KDE的常用工具集,應該包含類似的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.