Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Hack for opening arbitrary files in gnome using their default program

View go2.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#! /usr/bin/env python
# encoding: utf-8
# Written by Morten Minde Neergaard – m@8d.no
# 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
Something went wrong with that request. Please try again.