Python and the clipboard

I liked the idea (found via Alex) of modifying clipboard data in place, and decided to steal it for my own use, in python, on win32 and ubuntu. Since it was surprisingly annoying to figure out how to use the clipboard in either case, I’ll post what I ended up with, so that I can find it again myself.

This works with gtk or win32; the latter requires pywin32:

#! /usr/bin/env python2.5

from __future__ import with_statement
from contextlib import contextmanager

try:
    import win32clipboard as wcb
    import win32con

    @contextmanager
    def WinClipboard():
        """
        A context manager for using the windows clipboard safely.
        """
        try:
            wcb.OpenClipboard()
            yield
        finally:
            wcb.CloseClipboard()

    def getcbtext():
        with WinClipboard():
            return wcb.GetClipboardData(win32con.CF_TEXT)

    def setcbtext(text):
        with WinClipboard():
            wcb.EmptyClipboard()
            wcb.SetClipboardText(text)

except ImportError, e:
    # try gtk.  If that doesn't work, just let the exception go
    import gtk

    def getcbtext():
        return gtk.Clipboard().wait_for_text()

    def setcbtext(text):
        cb = gtk.Clipboard()
        cb.set_text(text)
        cb.store()

def replaceclipboard(fn):
    """
    Modify text on the clipboard.

    fn: a callable object that maps strings to strings.

    >>> setcbtext("This is some text.")
    >>> replaceclipboard(lambda s : s.upper())
    >>> getcbtext()
    'THIS IS SOME TEXT.'
    """
    text = getcbtext()
    newtext = fn(text)
    setcbtext(newtext)

def _test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    _test()
Advertisements

Tags: ,

One Response to “Python and the clipboard”

  1. konsumer Says:

    I couldn’t get this to work on Ubuntu 9.04, in the direction of inserting text into the clipboard.

    >>> import clip
    >>> clip.setcbtext(‘Hello from clip!’)
    >>> clip.getcbtext()
    ‘Hello from clip!’

    That works, but the clipboard doesn’t carry over to other windows (like Gedit.)

    On Edit->Paste, or Ctrl-V, the buffer is empty.

    Tested with Gedit and this textarea.

    I can read the clipboard from python, though (if I copy something in Gedit)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: