Python Friday #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.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

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:

 

Write to the clipboard

We can write to the clipboard with this code:

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:

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.