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 document icon in Explorer or Finder. What is the best way to do this in Python?
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.