How do I read text from the clipboard? How do I read text from the clipboard? python python

How do I read text from the clipboard?


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 datawin32clipboard.OpenClipboard()win32clipboard.EmptyClipboard()win32clipboard.SetClipboardText('testing 123')win32clipboard.CloseClipboard()# get clipboard datawin32clipboard.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.xTk().clipboard_get()


I found out this was the easiest way to get access to the clipboard from python:

1) Install pyperclip:pip install pyperclip

2) Usage:

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

Tested on Win10 64-bit, Python 3.5 and Python 3.7.3 (64-bit). Seems to work with non-ASCII characters, too. Tested characters include ±°©©αβγθΔΨΦåäö