149

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

Foo42
  • 3,024
  • 4
  • 22
  • 17
  • 5
    Related to [this question](http://stackoverflow.com/q/579687/296974). – glglgl Nov 15 '12 at 13:48
  • in my case, only [dan](http://stackoverflow.com/users/2084578/dan) answer worked , which uses [clipboard](https://pypi.python.org/pypi/clipboard/0.0.4) package. – Soorena Oct 09 '16 at 13:04

15 Answers15

146

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.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Sakin
  • 3,367
  • 3
  • 23
  • 27
  • 8
    Do you know if there is a way to use the `with´ statement ? – Norfeldt Jul 11 '13 at 14:21
  • 4
    Worth noting, in py34, win7, SetClipboardText did not work without a preceding call to EmptyClipboard – CoderTao Jan 12 '15 at 21:57
  • This module is useful if you want to perform more complex operations, e.g. getting the HTML-formatted content out of clipboard. See http://stackoverflow.com/questions/17298897/how-can-i-copy-from-an-html-file-to-the-clipboard-in-python-in-formatted-text – xji Sep 08 '16 at 08:23
  • 2
    @Norfeldt If there is no native way, you can easily create your own custom object that supports "with" – Elijas Dapšauskas Jun 28 '18 at 18:38
  • Not working if I tried to copy a text with multiline using a string variable defined with """ – Rodrigo Vieira Dec 06 '20 at 21:19
80

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()
kmonsoor
  • 7,600
  • 7
  • 41
  • 55
  • 3
    Far better imo than trying to get `pywin32` installed, as that has a spate of known issues. Good tip on the casing difference, was hard to catch at first. – Adrian Larson Jan 27 '21 at 18:39
  • For me this creates a leftover Tk() window which is frustrating (and uses up resources). If you're doing this as a one-off, it can be prevented with a couple more lines: ```a = Tk(); clipboard = a.clipboard_get(); a.destroy()``` – user2979044 May 23 '23 at 20:58
56

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

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

Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
  • does it suitable for 3.6? it is installed succesfully but when used paste () method it gives me error:" from PySide import __version__ as PYSIDE_VERSION # analysis:ignore ModuleNotFoundError: No module named 'PySide' ". When i tried installing Pyside it says it is not supported in 3.6 – gaurav Mar 30 '20 at 06:04
  • Yes it should work on Python 3.6, and I just tested with Python 3.7.4 (64-bit). Looking the [setup.py](https://github.com/asweigart/pyperclip/blob/master/setup.py) of the package it should have no dependencies to Pyside or any other packages. Are you sure that the paste command is trying to use Pyside? – Niko Föhr Mar 30 '20 at 08:03
  • Yes, paste command is looking for Pyside and as Pyside only supports upto python 3.4 it gives error – gaurav Apr 02 '20 at 06:01
  • It seems to be the most simple solution for WSL with python3.6 – enoted Sep 09 '20 at 10:55
  • 1
    I used pip to install `clipboard` package which only has one line `from pyperclip import copy, paste` LOL. `pyperclib` is the perfect solution. – Lê Quang Duy Jan 09 '21 at 09:07
  • 3
    pyperclip also works on Mac and Linux too (not just Windows), which is nice. – David Foster Mar 04 '21 at 15:37
27

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())
kichik
  • 33,220
  • 7
  • 94
  • 114
23

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: How do I copy a string to the clipboard on Windows using Python?

Plus, Tkinter is in the python standard library.

Community
  • 1
  • 1
Buttons840
  • 9,239
  • 15
  • 58
  • 85
  • 3
    Some code that will get the clipboard value via Tkinter: from Tkinter import Tk [\nl] r = Tk() [\nl] result = r.selection_get(selection = "CLIPBOARD") [\nl] r.destroy() – mgkrebbs Jan 08 '14 at 00:42
  • It's certainly easy, but it may change the window focus momentarily causing window flicker. It's probably worth coding for win32clipboard if it's available, falling back to Tkinter if not. – Keeely Nov 18 '21 at 11:29
14

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()
born
  • 656
  • 1
  • 6
  • 21
12

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()
ankostis
  • 8,579
  • 3
  • 47
  • 61
Paul Sumpner
  • 447
  • 7
  • 8
6

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.

user136036
  • 11,228
  • 6
  • 46
  • 46
4

Use Pythons library Clipboard

Its simply used like this:

import clipboard
clipboard.copy("this text is now in the clipboard")
print clipboard.paste()  
Dan
  • 147
  • 1
  • 4
  • 16
    This is essentially using pyperclip. The entire source code of this module is literally: `from pyperclip import copy, paste`. – pbreach Oct 11 '17 at 15:12
  • 1
    it's true. However they are right that `clipboard` is a better name. This function should be included in Python standard library. – Vincenzooo Oct 09 '20 at 21:19
  • 2
    this kind of package is just a shame... with one line of code that just uses another package... – jdhao Feb 03 '21 at 07:50
  • 1
    `import pyperclip as clipboard` – John Feb 20 '23 at 07:43
  • @jdhao It's also kinda funny if you think about it... Maybe they used the `pyperclip` module to copy some code to the clipboard in order to make the `clipboard` module with! – Andrew Jun 23 '23 at 15:11
3

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/

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
3
import pandas as pd
df = pd.read_clipboard()
Athii
  • 130
  • 2
  • 11
  • 2
    This works best for me as I already have a dependency on Pandas. The implementation behind this resides in `pandas.io.clipboard.clipboard_get()`, which is more useful if you need text without parsing it. – Yuval Apr 12 '22 at 08:24
2

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

Why not try calling powershell?

import subprocess

def getClipboard():
    ret = subprocess.getoutput("powershell.exe -Command Get-Clipboard")
    return ret
  • Wow, I didn't know we can do that, just like on Linux and the like, the best solution for me! – mwo Jul 13 '22 at 18:02
0

A not very direct trick:

Use pyautogui hotkey:

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

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

see2
  • 17
  • 1
0

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

asdf101
  • 569
  • 5
  • 18