3

How do I paste HTML data from the X clipboard using PyGTK/GTK+?

I would need something like xclip, but with the ability to output clipboard data as HTML, not just as plain text. I'm using PyGTK, but I am not afraid of plain GTK+ in C.

I've read GtkClipboard and PyGTK's gtk.Clipboard references, and I've found this question, but I would need a small example to get me started.

Community
  • 1
  • 1
Danilo Piazzalunga
  • 7,590
  • 5
  • 49
  • 75

1 Answers1

2

Updated answer

The original answer (below) used an old API, here is an updated version:

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk

clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
text = clipboard.wait_for_contents(Gdk.Atom.intern("text/html", True))
print(text.get_data())

Note also that your application may use a different target than "text/html": you can check which targets are available with:

def get_targets(clipboard, targets, n_targets):
    assert len(targets) == n_targets
    print(f"There are {n_targets} targets:")
    print("\n".join(map(str, targets)))

clipboard.request_targets(get_targets)

Original answer

Found it. I used something like this:

clipboard = gtk.Clipboard()
target = "text/html"
clipboard.wait_for_contents(target)
clipboard.request_contents(target, dump_clipboard_callback)

And then the callback function can simply extract the data:

def dump_clipboard_callback(clipboard, selection_data, data=None):
    print selection_data.data
tiho
  • 6,655
  • 3
  • 31
  • 31
Danilo Piazzalunga
  • 7,590
  • 5
  • 49
  • 75
  • 3
    I believe `wait_for_contents` here is redundant. You either use `request contents` with a callback, or `wait_for_contents` and use its return value. Note that both methods go back into the main loop, so you won't block if you use wait_for_contents. – Matthew Jul 10 '12 at 17:54