How do I read text from the clipboard?

PythonWindowsInteropClipboard

Python Problem Overview


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

Python Solutions


Solution 1 - 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.

Solution 2 - Python

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()

Solution 3 - Python

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 ±°©©αβγθΔΨΦåäö

Solution 4 - Python

I've seen many suggestions to use the win32 module, but Tkinter provides the shortest and easiest method I've seen, as in this post: https://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python/4203897#4203897

Plus, Tkinter is in the python standard library.

Solution 5 - Python

If you don't want to install extra packages, ctypes can get the job done as well.

import ctypes

CF_TEXT = 1

kernel32 = ctypes.windll.kernel32
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
user32 = ctypes.windll.user32
user32.GetClipboardData.restype = ctypes.c_void_p

def get_clipboard_text():
    user32.OpenClipboard(0)
    try:
        if user32.IsClipboardFormatAvailable(CF_TEXT):
            data = user32.GetClipboardData(CF_TEXT)
            data_locked = kernel32.GlobalLock(data)
            text = ctypes.c_char_p(data_locked)
            value = text.value
            kernel32.GlobalUnlock(data_locked)
            return value
    finally:
        user32.CloseClipboard()

print(get_clipboard_text())

Solution 6 - Python

The most upvoted answer above is weird in a way that it simply clears the Clipboard and then gets the content (which is then empty). One could clear the clipboard to be sure that some clipboard content type like "formated text" does not "cover" your plain text content you want to save in the clipboard.

The following piece of code replaces all newlines in the clipboard by spaces, then removes all double spaces and finally saves the content back to the clipboard:

import win32clipboard

win32clipboard.OpenClipboard()
c = win32clipboard.GetClipboardData()
win32clipboard.EmptyClipboard()
c = c.replace('\n', ' ')
c = c.replace('\r', ' ')
while c.find('  ') != -1:
    c = c.replace('  ', ' ')
win32clipboard.SetClipboardText(c)
win32clipboard.CloseClipboard()

Solution 7 - Python

The python standard library does it...

try:
    # Python3
    import tkinter as tk
except ImportError:
    # Python2
    import Tkinter as tk

def getClipboardText():
    root = tk.Tk()
    # keep the window from showing
    root.withdraw()
    return root.clipboard_get()

Solution 8 - Python

Use Pythons library https://pypi.python.org/pypi/clipboard/0.0.4">Clipboard

Its simply used like this:

import clipboard
clipboard.copy("this text is now in the clipboard")
print clipboard.paste()  

Solution 9 - Python

Try win32clipboard from the win32all package (that's probably installed if you're on ActiveState Python).

See sample here: http://code.activestate.com/recipes/474121/

Solution 10 - Python

For my console program the answers with tkinter above did not quite work for me because the .destroy() always gave an error,:

> can't invoke "event" command: application has been destroyed while executing...

or when using .withdraw() the console window did not get the focus back.

To solve this you also have to call .update() before the .destroy(). Example:

# Python 3
import tkinter

r = tkinter.Tk()
text = r.clipboard_get()
r.withdraw()
r.update()
r.destroy()

The r.withdraw() prevents the frame from showing for a milisecond, and then it will be destroyed giving the focus back to the console.

Solution 11 - Python

A not very direct trick:

Use pyautogui hotkey:

Import pyautogui
pyautogui.hotkey('ctrl', 'v')

Therefore, you can paste the clipboard data as you like.

Solution 12 - Python

After whole 12 years, I have a solution and you can use it without installing any package.

from tkinter import Tk, TclError
from time import sleep

while True:
    try:
        clipboard = Tk().clipboard_get()
        print(clipboard)
        sleep(5)
    except TclError:
        print("Clipboard is empty.")
        sleep(5)

Solution 13 - Python

For users of Anaconda: distributions don't come with pyperclip, but they do come with pandas which redistributes pyperclip:

>>> from pandas.io.clipboard import clipboard_get, clipboard_set
>>> clipboard_get()
'from pandas.io.clipboard import clipboard_get, clipboard_set'
>>> clipboard_set("Hello clipboard!")
>>> clipboard_get()
'Hello clipboard!'

I find this easier to use than pywin32 (which is also included in distributions).

Solution 14 - Python

import pandas as pd
df = pd.read_clipboard()

Solution 15 - Python

Why not try calling powershell?

import subprocess

def getClipboard():
	ret = subprocess.getoutput("powershell.exe -Command Get-Clipboard")
	return ret

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFoo42View Question on Stackoverflow
Solution 1 - PythonSakinView Answer on Stackoverflow
Solution 2 - PythonkmonsoorView Answer on Stackoverflow
Solution 3 - Pythonnp8View Answer on Stackoverflow
Solution 4 - PythonButtons840View Answer on Stackoverflow
Solution 5 - PythonkichikView Answer on Stackoverflow
Solution 6 - PythonbornView Answer on Stackoverflow
Solution 7 - PythonPaul SumpnerView Answer on Stackoverflow
Solution 8 - PythonDanView Answer on Stackoverflow
Solution 9 - PythonEli BenderskyView Answer on Stackoverflow
Solution 10 - Pythonuser136036View Answer on Stackoverflow
Solution 11 - Pythonsee2View Answer on Stackoverflow
Solution 12 - Pythonkirgizmustafa17View Answer on Stackoverflow
Solution 13 - Pythonasdf101View Answer on Stackoverflow
Solution 14 - PythonAthiiView Answer on Stackoverflow
Solution 15 - Python东临碣石View Answer on Stackoverflow