Skip to content

#129: Copy & Paste With Python

For some problems it would be great if our application could access the clipboard of the current user and do some copy & paste actions. Let's look how we can access the clipboard from Python.

Install pyperclip

Pyperclip is one of multiple libraries we can use for this task. I choose pyperclip because it is straightforward to use and works on Windows, Linux and Mac. You can install it with this command:

pip install pyperclip

Write to the clipboard

We can write to the clipboard with this code:

1
2
3
4
import pyperclip

# write to the clipboard
pyperclip.copy("a new value for the clipboard")

If we run this code, the text "a new value for the clipboard" gets copied into our clipboard and we can paste it with CTRL-P to any location we like.

Read from the clipboard

We can read the content of the clipboard with this code:

1
2
3
4
5
6
import pyperclip

#read from the clipboard
text = pyperclip.paste()

print(text)

Whatever text or number we had in the clipboard is printed out. You can play around and as you change the content of your clipboard; the output will change as well.

Conclusion

Pyperclip offers us a simple way to access the clipboard. Without the need for a graphical user interface, we can offer an intuitive way to interact with the user and get work done without much interference.