How to read text from the clipboard with Python?

Sometimes, we want to read text from the clipboard with Python.

In this article, we’ll look at how to read text from the clipboard with Python.

How to read text from the clipboard with Python?

To read text from the clipboard with Python, we can use the pywin32 library.

For instance, we write

pip install pywin32

Then we use it by writing

import win32clipboard

win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()

win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print(data)

We copy the 'testing 123' string to the clipboard with

win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()

And then we get the copied value from the clipboard with

win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print(data)

Conclusion

To read text from the clipboard with Python, we can use the pywin32 library.