We will be using the pyperclip module in order to copy and paste content to the clipboard. It is cross−platform and works on both Python 2 and Python 3.
Copying and pasting from and to the clipboard could be very useful when you want the output of the data to be pasted elsewhere in a different file or software.
The pyperclip module does not come packaged with Python. In order to access it, you must first download and install it. You can do this using the PIP package manager.
Launch your terminal and type the command below to install pyperclip
pip install pyperclip
Once you have it installed, you must import it to your python script.
We can do this using the import command,
In order to copy text to the clipboard we use the pyperclip.copy() function.
import pyperclip pyperclip.copy("Hello world!")
The above lines of code will copy “Hello world!” to your clipboard and would be ready to paste.
import pyperclip text = pyperclip.paste() print(text)
We use the pyperclip.paste() function to paste the latest content present in the clipboard.
Sometimes while working on a project you might want to paste new messages after you copy a different message.
In order to achieve this, we use the pyperclip. waitForNewPaste() function.
import pyperclip pyperclip.copy("Hello world!") text = pyperclip.paste() print(text) pyperclip.copy('Hello world!') text = pyperclip.waitForNewPaste() print(text)
Hello world! Random message copied
Note − In the above example, the program would terminate after it prints out the new copies text. The new copied text should be anything but “Hello world!”.
If you want to just paste, even if the text is same as the already existing text in the clip board, just go for pyperclip.waitForPaste() function.
Data stored in the clipboard and pasted is always a String datatype.
You now know how to copy and paste text or string datatype into your clipboard for quick access.
You can use this for developing simple automation tools that help you build tables, where data has to be constantly copied and pasted.
There are various other scenarios you can use this module in. And since it’s cross−platform, you can work with it on Linux, MacOS and Windows.