Python: Opening a folder in Explorer/Nautilus/Finder

Viewed 31427

I'm in Python, and I have the path of a certain folder. I want to open it using the default folder explorer for that system. For example, if it's a Windows computer, I want to use Explorer, if it's Linux, I want to use Nautilus or whatever is the default there, if it's Mac, I want to use Finder.

How can I do that?

5 Answers

One approach to something like this is maybe to prioritize readability, and prepare the code in such a manner that extracting abstractions is easy. You could take advantage of python higher order functions capabilities and go along these lines, throwing an exception if the proper function assignment cannot be made when a specific platform is not supported.

import subprocess
import sys


class UnsupportedPlatformException(Exception):
    pass


def _show_file_darwin():
    subprocess.check_call(["open", "--", path])

def _show_file_linux():
    subprocess.check_call(["xdg-open", "--", path])

def _show_file_win32():
    subprocess.check_call(["explorer", "/select", path])

_show_file_func = {'darwin': _show_file_darwin, 
                   'linux': _show_file_linux,
                   'win32': _show_file_win32}

try:
    show_file = _show_file_func[sys.platform]
except KeyError:
    raise UnsupportedPlatformException


# then call show_file() as usual
Related