Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy HTML to clipboard with PyGObject

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.)

like image 402
Craig McQueen Avatar asked Sep 03 '25 03:09

Craig McQueen


2 Answers

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)
like image 80
Udi Avatar answered Sep 05 '25 22:09

Udi


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...
like image 37
Simon Feltman Avatar answered Sep 06 '25 00:09

Simon Feltman