如果我可以避免的话,我宁愿不要把它弄得一团糟。
Weeell 我认为您将需要一点平台嗅探工具,但希望不像可怕的命令嗅探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 版本当前会因文件名中的空格而失败。 Bug 2304 可能与此有关,但参数转义和 Windows shell (cmd /c ...) 似乎确实存在一个基本问题,因为您不能嵌套双引号,也不能 ^-转义引号或空格。我还没有找到任何方法来从命令行引用和运行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])