python文件运行在浏览器中打开_是否有跨平台的方式在Python中打开文件浏览器?...

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 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

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'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])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值