Created
May 19, 2011 01:34
-
-
Save xim/979990 to your computer and use it in GitHub Desktop.
Hack for opening arbitrary files in gnome using their default program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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