Skip to content

Instantly share code, notes, and snippets.

@xim
Created May 19, 2011 01:34
Show Gist options
  • Save xim/979990 to your computer and use it in GitHub Desktop.
Save xim/979990 to your computer and use it in GitHub Desktop.
Hack for opening arbitrary files in gnome using their default program
#! /usr/bin/env python
# encoding: utf-8
# Written by Morten Minde Neergaard – [email protected]
# Based on idea from http://therning.org/magnus/archives/251
"""
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
return subprocess.call(app)
def open_files(verbose, *filenames):
success = 0
for filename in filenames:
mime_app = None
gfile = gio.File(filename)
try:
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:
try:
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'
else:
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:
sys.argv.remove(arg)
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