[英]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.