Create a gist now

Instantly share code, notes, and snippets.

@xim /
Created May 19, 2011

What would you like to do?
Hack for opening arbitrary files in gnome using their default program
#! /usr/bin/env python
# encoding: utf-8
# Written by Morten Minde Neergaard –
# Based on idea from
Open a file in a manner similar to gnome-open.
Fall back to using xdg-open.
Return code: The sum of all return codes given by the called programs.
import gio
import os
import re
import subprocess
import sys
def call_opener(verbose, app, filename=None):
if app is None:
app = 'xdg-open %(file)s'
filename = {'file': filename}
app = [part % filename for part in app.split() if part]
sys.stderr.write('> %s\n' % ' '.join(app))
if verbose: print "calling", app
def open_files(verbose, *filenames):
success = 0
for filename in filenames:
mime_app = None
gfile = gio.File(filename)
gapp = gfile.query_default_handler()
mime_app = gapp.get_commandline()
if verbose: print "gfile handler", gapp, mime_app
mime_app = re.sub('%[uf]', '%(file)s', mime_app, flags=re.IGNORECASE)
if not '%(file)s' in mime_app:
mime_app += ' %(file)s'
except gio.Error:
mime_type = gfile.query_info('standard::*').get_content_type()
mime_type = gio.content_type_get_mime_type(mime_type)
except gio.Error:
mime_type = gio.content_type_guess(filename)
retcode = call_opener('/usr/bin/see --norun %(file)s', '%s:%s' %
(mime_type, filename))
if verbose: print "see --norun '%s:%s' returned %d" % (mime_type, filename, retcode)
if retcode:
retcode = call_opener('/usr/bin/see --norun %(file)s', filename)
if not retcode:
mime_app = '/usr/bin/see %(file)s'
mime_app = '/usr/bin/see %(file)s'
if verbose: print "see --norun '%s:%s' returned %d" % (mime_type, filename, retcode)
filename = '%s:%s' % (mime_type, filename)
success += call_opener(verbose, mime_app, filename)
return success
if __name__ == '__main__':
verbose = False
for arg in ['-v', '--verbose']:
if arg in sys.argv:
verbose = True
sys.exit(open_files(verbose, *sys.argv[1:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment