Copy and paste to your clipboard using the pyperclip module in Python


Introduction

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.

Getting Started

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,

import pyperclip

Copying text to the clipboard

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.

Pasting text from the clipboard

Example

import pyperclip
text = pyperclip.paste()
print(text)

Output

Hello world!

We use the pyperclip.paste() function to paste the latest content present in the clipboard.

Pasting content after copying new content

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.

Example

import pyperclip
pyperclip.copy("Hello world!")
text = pyperclip.paste()
print(text)
pyperclip.copy('Hello world!')
text = pyperclip.waitForNewPaste()
print(text)

Output

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.

Conclusion

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.

Updated on: 11-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements