Pyperclip – A cross-platform clipboard module for Python

I got tired of not having a good cross-platform module for accessing the clipboard in Python, so I put this together. It is a module that loads a copy() and paste() function depending on what your operating system (or window manager) is.

It has the following requirements:

  • Windows - No requirements. You don’t need the win32 module installed.
  • Mac - Requires the pbcopy and pbpaste, which come with OS X.
  • Linux - Requires the xclip command, which possibly comes with the os. If not, run sudo apt-get install xclip. Or have the gtk or PyQt4 modules installed. Also can use the xsel command.
  • Pyperclip runs on both Python 2 and Python 3.

Usage is simple:

import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()

UPDATE: (8/16/2014) Download Pyperclip from PyPI.

UPDATE: (9/13/2011) I’ve fixed a small TypeError that some people were coming across that Gustav pointed out below.

UPDATE: Kenneth Reitz pointed out that he’s coded a similar module called Xerox. I missed it in my prior art search. It seems to have a fairly similar implementation as Pyperclip, except requires the win32 Python module to work on Windows.

I’m busy trying to figure out X11 programming so I can get rid of the xclip dependency.

2 Responses to “Pyperclip – A cross-platform clipboard module for Python”

  1. Craig McQueen Says:

    I see the download file says it’s version 1.4. But PyPI still has version 1.3.

  2. Steve Elam Says:

    Another platform to support is cygwin which is able to access the windows user32 dll through ctypes.cdll instead of ctypes.windll. I was able to support the python distrubuted with cygwin with the following additions to

    def cygwinGetClipboard():
    pcontents = ctypes.cdll.user32.GetClipboardData(1) # 1 is CF_TEXT
    data = ctypes.c_char_p(pcontents).value
    return data

    def cygwinSetClipboard(text):
    text = str(text)
    GMEM_DDESHARE = 0×2000
    # works on Python 2 (bytes() only takes one argument)
    hCd = ctypes.cdll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text))+1)
    except TypeError:
    # works on Python 3 (bytes() requires an encoding)
    hCd = ctypes.cdll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text, ‘ascii’))+1)
    pchData = ctypes.cdll.kernel32.GlobalLock(hCd)
    # works on Python 2 (bytes() only takes one argument)
    ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
    except TypeError:
    # works on Python 3 (bytes() requires an encoding)
    ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text, ‘ascii’))
    ctypes.cdll.user32.SetClipboardData(1, hCd)

    elif platform.system()[0:6] == ‘CYGWIN’:
    import ctypes
    getcb = cygwinGetClipboard
    setcb = cygwinSetClipboard

Leave a Reply

free blog themes