Saturday 16 September 2017

Using pyperclip for working with the clipboard

In this article I'll walk you through using a nice python module named pyperclip. It's really easy to use. I'll be working on a Centos 7 system with gnome GUI interface.

So, let's install the pyperclip module via pip.



Now that the module is isntalled let's write a quick script to demonstrate its usage.

[root@still ~]# cat clip.py 
#!/usr/bin/python

import pyperclip

pyperclip.copy('Hello World')

print pyperclip.paste()
[root@still ~]#


This script when executed gives the below output:

[root@still ~]# ./clip.py 
Hello World
[root@still ~]# 


To use the module we first import it into our script.
Next we copy the strings 'Hello World' to the clipboard via pyperclip's copy function and then print out the contents of the clipboard with pyperclip paste function.

As another example I've jus copied the output of the ls command to the clipboard as shown below:



I've commented out the pyperclip copy function and just left the paste function as it is. Let's execute the script:



As you can see the pyperclip.paste function dumps the content of the clipboard to the screen.

I tried doing the same thing using the command line but it didn't work and kept getting a "You don't have a copy/paste utility" error.
The cause of this error appears to be the fact that when we are working on the Linux command line via an ssh session then we have access to the Windows clipboard and our Linux server computers which generally will not have a GUI wouldn't really have a clipboard.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...