Python – How to Copy and Paste to the Clipboard in Linux

If you’re on a Linux system, you can use the pyGTK library. It’s got a clipboard feature.

Here’s how to use it (code thanks to Thomas Lee):

import pygtk
import gtk

# get the clipboard
clipboard = gtk.clipboard_get()

# read the clipboard text data. you can also read image and
# rich text clipboard data with the
# wait_for_image and wait_for_rich_text methods.
text = clipboard.wait_for_text()

# set the clipboard text data

# make our data available to other applications

Here is the gtk.clipboard documentation.

Another Alternative

An alternative to the GTK library is the Xsel command line program. It should work for any Linux (or Unix?) with X.

And this is how you would use it (at least according to these guys):

#Copy from the clipboard:
import os
s = popen('xsel').read()

#Paste to the clipboard:
import os
os.popen('xsel', 'wb').write(s)

3 Responses to “Python – How to Copy and Paste to the Clipboard in Linux”

  1. ephemient says:

    pygtk should work without Gnome. xclip works too.

  2. James Thiele says:

    FYI on OS X there are pbcopy and pbpaste command line programs.

  3. Thanks for the tips guys. I’ll update the post to say it will work without Gnome.