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

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.

Leave a Comment