gpt4 book ai didi

python - 在 Windows 和 Mac OS 中使用 Python 中的默认 OS 应用程序打开文档

转载 作者:IT老高 更新时间:2023-10-28 21:06:29 25 4
gpt4 key购买 nike

我需要能够在 Windows 和 Mac OS 中使用其默认应用程序打开文档。基本上,我想做与在资源管理器或 Finder 中双击文档图标时发生的相同的事情。在 Python 中执行此操作的最佳方法是什么?

最佳答案

使用 Python 2.4+ 上可用的 subprocess 模块,而不是 os.system(),因此您不必处理 shell 转义。

import subprocess, os, platform
if platform.system() == 'Darwin': # macOS
subprocess.call(('open', filepath))
elif platform.system() == 'Windows': # Windows
os.startfile(filepath)
else: # linux variants
subprocess.call(('xdg-open', filepath))

双括号是因为 subprocess.call() 想要一个序列作为它的第一个参数,所以我们在这里使用一个元组。在带有 Gnome 的 Linux 系统上,还有一个 gnome-open 命令可以执行相同的操作,但 xdg-open 是 Free Desktop Foundation 标准,并且适用于 Linux 桌面环境。

关于python - 在 Windows 和 Mac OS 中使用 Python 中的默认 OS 应用程序打开文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/434597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com