1

I'm writing a PyGTK GUI application in Ubuntu to browse some images, and I'd like to open an image in the default image viewer application when it is double-clicked (like when it is opened in Nautilus).
How can I do it?

mooware
  • 1,722
  • 2
  • 16
  • 25

3 Answers3

3

In GNU/Linux use xdg-open, in Mac use open, in Windows use start. Also, use subprocess, if not you risk to block your application when you call the external app.

This is my implementation, hope it helps: http://goo.gl/xebnV

import sys
import subprocess
import webbrowser

def default_open(something_to_open):
    """
    Open given file with default user program.
    """
    # Check if URL
    if something_to_open.startswith('http') or something_to_open.endswith('.html'):
        webbrowser.open(something_to_open)
        return 0

    ret_code = 0

    if sys.platform.startswith('linux'):
        ret_code = subprocess.call(['xdg-open', something_to_open])

    elif sys.platform.startswith('darwin'):
        ret_code = subprocess.call(['open', something_to_open])

    elif sys.platform.startswith('win'):
        ret_code = subprocess.call(['start', something_to_open], shell=True)

    return ret_code
Havok
  • 5,776
  • 1
  • 35
  • 44
3

I don't know specifically using PyGTK but: xdg-open opens the default app for a file so running something like this should work:

import os
os.system('xdg-open ./img.jpg')

EDIT: I'd suggest using the subprocess module as in the comments. I'm not sure exactly how to use it yet so I just used os.system in the example to show xdg-open.

avacariu
  • 2,780
  • 3
  • 25
  • 25
  • 1
    Useless use of `system`. This should be `subprocess.check_call(["xdg-open", filename])`. – Philipp Aug 07 '10 at 16:46
  • 1
    The `subprocess` module is aimed at replacing older functions like `os.system`: http://docs.python.org/library/subprocess.html – avacariu Aug 07 '10 at 21:57
2

GTK (>= 2.14) has gtk_show_uri:

gtk.show_uri(screen, uri, timestamp)

Example usage:

gtk.show_uri(None, "file:///etc/passwd", gtk.gdk.CURRENT_TIME)

Related

Community
  • 1
  • 1
Bruce van der Kooij
  • 2,192
  • 1
  • 18
  • 29