Open document with default OS application in Python, both in Windows and Mac OS

前端 未结 13 1317
刺人心
刺人心 2020-11-22 10:36

I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the do

相关标签:
13条回答
  • 2020-11-22 11:24

    Use the subprocess module available on Python 2.4+, not os.system(), so you don't have to deal with shell escaping.

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

    The double parentheses are because subprocess.call() wants a sequence as its first argument, so we're using a tuple here. On Linux systems with Gnome there is also a gnome-open command that does the same thing, but xdg-open is the Free Desktop Foundation standard and works across Linux desktop environments.

    0 讨论(0)
提交回复
热议问题