I have the following script clip-test.py
:
#!/usr/bin/python
import gtk
gtk.Clipboard().set_text("exciting clipboard contents")
gtk.Clipboard().set_can_store(None) # not sure if these last two lines are useful
gtk.Clipboard().store()
When I run this like so:
python clip-test.py
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 clip-test.py
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 display
and selection
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?
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:
The
set_can_store()
andstore()
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 callingset_can_store([("UTF8_STRING", 0, 0)])
instead ofset_can_store(None)
.