How-to Access the Windows Clipboard with Python
Introduction
I’m writing a script to generate some text that I would need to copy and paste into a form on a website. Wouldn’t it be easier if Python could copy the text to the clipboard directly and save me a click?
This will be done on a Windows 10 PC with Python 3 (3.8.1 specifically).
Required Libraries
It seems that this is not nearly as straightforward as I thought it might be. This seems largely to do with the fact that I want to do it on Windows as opposed to (possibly) Linux. The first result from Google forwards me to a big ol’ list of things I can try which seem somewhat involved. I don’t really want to install TKinter in order to just get the clipboard.
The first result seems to have a straightforward answer: use Pyperclip.
Hopefully this is something that pip can install for me. Let’s try.
I did the following:
Whew! That was easy.
Copying Text to the Clipboard
The SO answer from above has this code snippet:
I pasted that into a new Python script, ran it, and was able to paste the contents of the clipboard and verify that it was the copied string.
Bueno!
Retrieving Text From the Clipboard
I’m guessing it’s as easy as the ‘paste’ command seen in the previous script. I didn’t check the result of the paste command, so we’ll add a print statement to see. Here’s what the script looks like now:
And this script produces the following:
Looks right to me!