是否有跨平台的方式在Python中打开文件浏览器? [英] Is there a cross-platform way to open a file browser in Python?
问题描述
我在考虑 webbrowser 模块的思路,但是对于文件浏览器.在Windows中,我想打开资源管理器,在Linux上,我要打开nautilus,在KDE上,打开Konqueror,等等.如果可以避免的话,我不愿对其进行混淆. ;-)
I'm thinking something along the lines of the webbrowser module, but for file browsers. In Windows I'd like to open explorer, in GNOME on Linux I want to open nautilus, Konqueror on KDE, etc. I'd prefer not to kludge it up if I can avoid it. ;-)
推荐答案
如果我可以避免的话,我宁愿不加思索.
I'd prefer not to kludge it up if I can avoid it.
Weeell我认为您将需要一点平台嗅探功能,但希望不会像可怕的命令嗅探webbrowser
模块那么多.这是它的第一个刺路:
Weeell I think you are going to need a little bit of platform-sniffing kludge, but hopefully not as much as the ghastly command-sniffing webbrowser
module. Here's a first stab at it:
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 ...
),因为您不能嵌套双引号,也不能^-转义引号或空格.我根本找不到从命令行引用和运行cmd /c start C:\Documents and Settings
的任何方式.
Note the win32 version will currently fail for spaces in filenames. Bug 2304 might be something to do with that, but there does seem to be a basic problem with parameter escaping and the Windows shell (cmd /c ...
), in that you can't nest double-quotes and you can't ^-escape quotes or spaces. I haven't managed to find any way to quote and run cmd /c start C:\Documents and Settings
from the command line at all.
ETA re nosklo的评论:仅在Windows上,有一种内置方法:
ETA re nosklo's comment: on Windows only, there is a built-in way to do it:
if sys.platform=='win32':
os.startfile(d)
这是一种非常不错的替代解决方案,它可以找到外壳并用它打开一个文件夹,您现在不需要了,但我将继续.(部分原因是它可能用于其他用途,但主要是因为我花了时间打字该死的东西!)
Here's the not-very-nice alternative solution to find the shell and open a folder with it, which you shouldn't now need, but I'll leave in. (Partly because it might be of use for something else, but mostly because I spent the time to type the damned thing!)
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])
这篇关于是否有跨平台的方式在Python中打开文件浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!