A Simple Guide to Python Pyperclip Module

In the following article, we will try to uncover a fascinating library named Pyperclip. Al Sweigart is the creator of the Pyperclip module. He is also the author of the well-known python-beginners book, Automate the Boring Stuff with Python.

copy, clipboard & paste
copy, clipboard & paste

Everyone has used electronic devices like mobile phones, tablets, laptops, or computers. Likewise, they must have used the copy and paste functions. For instance, examples are many for copying/pasting OTPs, text messages, assignments, captions for Instagram posts. These functions have become a subconscious part of our daily lives.

Installing Pyperclip

Pyper clip is a cross-platform Python module that provides copy, paste clipboard functions. Using the specific command of your OS, install it, then you are good to go. However, please note you must have a version of python(2 or 3) installed on your machine.

Windows

pip install pyperclip

Linux / macOs

pip3 install pyperclip

Pycharm

conda install -c conda-forge pyperclip

Note: To install pyperclip in pycharm use the following steps, File -> Project -> Project Interperter -> click on the + button -> search “pyperclip” -> click on install button, for any other text editor simply import pyperclip in py script.

Importing Pyperclip

import pyperclip

Pyperclip’s methods & their working

Pyperclip has the following methods at its disposal.

  • .copy
  • .paste
  • .waitForPaste

Let’s elaborate on each of them using some examples:

.copy & .paste

import pyperclip as pyc

text_to_copy = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vel aliquam augue. Maecenas rutrum neque sit amet sodales interdum. Vestibulum a odio id magna faucibus efficitur a a lectus. Nulla a turpis vel leo aliquam commodo. Mauris et ex purus. Nam volutpat nunc non venenatis pellentesque. Nunc accumsan, est ac rutrum efficitur, quam dolor dignissim sem, ut vestibulum risus risus sit amet lectus. Donec sed interdum arcu."

pyc.copy(text_to_copy)
pyc.paste()

Let’s look at what is happening behind the scenes:

  • We have some randome lorem ipsum text stored in variable text_to_copy.
  • Then the pyperclip method .copy copies the entire text of of text_to_copy.
  • Clipboard of the OS stores it.
  • Clipboard is a buffer present in operating systems, temperorily created inside the ram. Generally used for data transfer among applications.
text copied and then pasted Pyperclip
text copied and then pasted

.waitForPaste

Example 1:

If some text is copied, it gets stored in the clipboard .waitForPaste waits for some plain text in the clipboard. It blocks and doesn’t return anything until it detects some text in the clipboard.

import pyperclip as pyc

pyc.waitForPaste()
pyc.paste()
pyperclip.waitForPaste() waiting for some text in clipboard Pyperclip
.waitForPaste() waiting for some text in clipboard

.waitForPaste waits for some plain text in the clipboard. It blocks and doesn’t return anything until it detects some text in the clipboard.

Lorem ipsum text on being copied gets printed to console Pyperclip
Lorem ipsum text on being copied gets printed to console

Example 2:

import pyperclip as pyc

text_to_copy = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vel aliquam augue. Maecenas rutrum neque sit amet sodales interdum. Vestibulum a odio id magna faucibus efficitur a a lectus. Nulla a turpis vel leo aliquam commodo. Mauris et ex purus. Nam volutpat nunc non venenatis pellentesque."

pyc.waitForPaste(text_to_copy)
pyc.paste()
Text gets replaced
Text gets replaced

Example 3:

Pyperclip.waitForPaste has a timeout parameter. It waits for that time and returns an exception.

import pyperclip as pyc

pyc.waitForPaste(10)
pyc.paste()
Pyperclip Exception raised if not text is copied for 10 sec
Exception raised if not text is copied for 10 sec

Copying a list to clipboard

import pyperclip

demo_list = ["text1","text2","text3","text4","text5"]

def list_copy_to_clipboard(list):
        if len(list) > 0:
            pyperclip.copy(', '.join(list))
            print('Copied to clipboard!')
            print(pyperclip.paste())
        else:
            print("There is nothing in the clipboard")

list_copy_to_clipboard(demo_list)
Copying list to clipboard
Copying list to the clipboard

Pyperclip alternative

Using xclip

Using the xclip command, we can directly copy the output to the clipboard. However, before using xclip, check it is installed or not by using which xclip command if it is not installed, use the following commands.

sudo apt-get update
sudo apt-get install xclip

Now that we have installed xclip, let’s see how we can copy to clipboard using xclip.

num = 10
print([i for i in range(num)])

The above code will return a list of numbers from 0-9. Now, if we want to copy the output to the clipboard, use xclip as follows. If you click on the mouse button, the output will be pasted.

python3 file.py | xclip

Using subprocess & xclip

import subprocess

def getClipboardData():
    p = subprocess.Popen(['xclip','-selection', 'clipboard', '-o'], stdout=subprocess.PIPE)
    retcode = p.wait()
    data = p.stdout.read()
    return data

def setClipboardData(data):
    p = subprocess.Popen(['xclip','-selection','clipboard'], stdin=subprocess.PIPE)
    p.stdin.write(data)
    p.stdin.close()
    retcode = p.wait()


setClipboardData("This text will be copied to clipboard".encode())
print(getClipboardData())
copy using subprocess & xclip
using subprocess

Note: xclip will work in Linux or macOS.

For windows

In windows, you can try out the following code.

import subprocess

def copy2clip(txt):
    cmd='echo '+txt.strip()+'|clip'
    return subprocess.check_call(cmd, shell=True)

FAQs

Using pyperclip in jupyter notebook

To use pyperclip in jupyter notebook, make sure you have it installed in your system. If you are using anaconda, try, conda install -c conda-forge pyperclip , for windows use pip install pyperclip & for Linux/macOS use pip3 install pyperclip. Then try importing it in the notebook.

Can I copy the image in the pyperclip?

No, since the pyperclip only supports plain text(int, str, boolean, float), hence, copying images isn’t possible.

Can we use the pyperclip in google collab?

Unfortunately, the pyperclip doesn’t work in collab. As collab runs on a server, therefore clipboard of the server is accessed not your system.

How to clear the clipboard using pyperclip?

In order to clear the clipboard, simply copy an empty string. For example:
import pyperclip
pyperclip.copy(' ')

Conclusion

In this article, we discussed an interesting module of Python called Pyperclip. We looked at its installation, various methods, and their working. I hope you learned something new today.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments