Is there an platform independent equivalent of os.startfile()?
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])
Just use webbrowser.open(filename)
. it can call os.startfile()
, open
, xdg-open
where appropriate.
Beware, there is a scary text in the docs:
Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.
It works fine for me. Test it in your environment.
Look at webbrower
's source code to see how much work needs to be done to be portable.
There is also an open issue on Python bug tracker -- Add shutil.open. "portable os.startfile()" interface turned out to be more complex than expected. You could try the submitted patches e.g., shutil.launch()
.