tobek tobek - 1 year ago 77
Python Question

Effect of PyGTK clipboard set_text persists only while process is running

I have the following script


import gtk

gtk.Clipboard().set_text("exciting clipboard contents")
gtk.Clipboard().set_can_store(None) # not sure if these last two lines are useful

When I run this like so:


it doesn't work. The clipboard is unchanged. We can elucidate the issue by running it in interactive mode and not letting the process finish:

python -i

Before leaving interactive mode, try pasting somewhere. The clipboard is changed; it works. After closing python, the clipboard returns to what it was before.

One thought was that this has something to do with which
clipboard the code is accessing by default, but I've tried varying those parameters and I still can't get it to work.

I'm using Python 2.7.3 and python-gtk2 2.24.0-3build1, running Kubuntu 13.04.

What gives?

Answer Source

This is not a GTK or PyGTK issue, but a consequence of how X11 copying and pasting works. When you press ^C in an X11 application, you haven't really copied anything yet, you have just instructed the application to remember the data for possible later use. Only when a "paste" is initiated does the data get transmitted to the paster. This saves resources and enables the copier and the paster to negotiate a data transfer format that best suits them. This is explained in some detail in the classic text by Jamie Zawinski.

Modern desktop environments do attempt to hold on to the clipboard contents, but you must enter the main loop and remain in it for long enough for the clipboard manager to grab your clipboard contents:


import gtk, gobject

gtk.Clipboard().set_text("exciting clipboard contents")
gobject.timeout_add(100, gtk.main_quit)

The set_can_store() and store() should be able to speed up the process, some googling showed that programs are using them to save the clipboard data in a destroy handler. It's not clear why it doesn't work for you — perhaps you should be calling set_can_store([("UTF8_STRING", 0, 0)]) instead of set_can_store(None).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download