Is there an platform independent equivalent of os.startfile()?

Lewistrick picture Lewistrick · Jun 26, 2013 · Viewed 18.4k times · Source

I want to run a program on several platforms (including Mac OS), so I try to keep it as platform independent as possible. I use Windows myself, and I have a line os.startfile(file). That works for me, but not on other platforms (I read in the documentation, I haven't tested for myself).

Is there an equivalent that works for all platforms?

By the way, the file is a .wav file, but I want users to be able to use their standard media player, so they can pause/rewind the file. That's why I use os.startfile(). I might be able to work with libraries that also allow playing/pausing/rewinding media files.

Answer

user4815162342 picture user4815162342 · Jun 26, 2013

It appears that a cross-platform file opening module does not yet exist, but you can rely on existing infrastructure of the popular systems. This snippet covers Windows, MacOS and Unix-like systems (Linux, FreeBSD, Solaris...):

import os, sys, subprocess

def open_file(filename):
    if sys.platform == "win32":
        os.startfile(filename)
    else:
        opener = "open" if sys.platform == "darwin" else "xdg-open"
        subprocess.call([opener, filename])