How do I read text from the clipboard?

How do I read text from the (windows) clipboard with python?


You can use the module called win32clipboard, which is part of pywin32.

Here is an example that first sets the clipboard data then gets it:

import win32clipboard

# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()

# get clipboard data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print data

An important reminder from the documentation:

When the window has finished examining or changing the clipboard, close the clipboard by calling CloseClipboard. This enables other windows to access the clipboard. Do not place an object on the clipboard after calling CloseClipboard.


you can easily get this done through the built-in module Tkinter which is basically a GUI library. This code creates a blank widget to get the clipboard content from OS.

from tkinter import Tk  # Python 3
#from Tkinter import Tk # for Python 2.x
Tk().clipboard_get()

I found pyperclip to be the easiest way to get access to the clipboard from python:

  1. Install pyperclip: pip install pyperclip

  2. Usage:

import pyperclip
    
s = pyperclip.paste()
pyperclip.copy(s)
    
# the type of s is string

With supports Windows, Linux and Mac, and seems to work with non-ASCII characters, too. Tested characters include ±°©©αβγθΔΨΦåäö