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

Question:

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.

Asked By: Lewistrick

||

Answers:

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])
Answered By: user4815162342

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

Answered By: jfs

It depend what you mean with platform independent. If your question is about how to open anything using the default action of the OS, for example, when you double click on some file to let the OS decide how to open it, then the simple answer is no.

However, to implement this functionality yourself, is very easy, but you need to use a few different methods to accommodate for different OS’s. That said, the most forgiving method is to use os.system(WinPathWithArgs) as I have explained in this answer.

Answered By: not2qubit

Try this:

import subprocess

subprocess.Popen(["open", 'directory'])
Answered By: Istiak Javed Anik

I built a small library combining the best options for cross-platform support:

$ pip install universal-startfile

then

from startfile import startfile

startfile("~/Downloads/example.png")
startfile("http://example.com")
Answered By: Jace Browning
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.