4

I'd like to copy HTML (and a plain text equivalent) to the clipboard in a Linux GUI environment. Cross-platform is ideal, although Linux is my immediate target. I'd also like to use something that works in Python 3.x as well as 2.x.

According to PyGObject docs, a Gtk.Clipboard object set_with_data() method should be suitable. But when I try to use it, there is no set_with_data member of the class.

>>> from gi.repository import Gtk, Gdk
>>> clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
>>> clipboard.set_with_data
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Clipboard' object has no attribute 'set_with_data'

How can I copy HTML plus plaintext to the clipboard using PyGObject?

(I might consider using PyGTK, however according to this answer it is deprecated and not supported in Python 3.x.)

Community
  • 1
  • 1
Craig McQueen
  • 41,871
  • 30
  • 130
  • 181

2 Answers2

3

I could not make this work from Python, but I found the following workaround using xclip:

import subprocess

s = "TEXT TO <b>COPY</b>!"
cmd = ["xclip", "-sel", "clip", "-t", "text/html", "-f"]
subprocess.check_output(cmd, input=s, text=True)
Udi
  • 29,222
  • 9
  • 96
  • 129
2

It looks like set_with_data() isn't exposed through introspection probably due to the function taking two C callbacks (not supported by introspection or bindings). See:
https://developer.gnome.org/gtk3/stable/gtk3-Clipboards.html#gtk-clipboard-set-with-data

This is a bug already logged with GTK+:
https://bugzilla.gnome.org/show_bug.cgi?id=656312

Some potential workarounds:

  • Limit your program to text only using clipboard.set_text() (breaks your requirement)
  • Write a C Python extension or even use introspection on your own shim library which gives a closure version of set_with_data(). It might also be possible to use something like ctypes, but probably painful.
  • Use PyGTK (which as you mentioned is no longer maintained) or another toolkit like PySide/Qt, wxPython, etc...
Simon Feltman
  • 1,120
  • 7
  • 8
  • That GTK+ bug is still marked "NEW" since August 2011. I can't hold my breath any longer. :) – Craig McQueen May 02 '17 at 23:49
  • The bug was moved to [GitLab](https://gitlab.gnome.org/GNOME/gtk/-/issues/364). That bug report said GTK4 has a new, better clipboard API, [`GdkClipboard`](https://docs.gtk.org/gdk4/class.Clipboard.html). – Craig McQueen May 03 '22 at 00:11