Project description
Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with Python 2 and 3.
Install on Windows: pip install pyperclip
Install on Linux/macOS: pip3 install pyperclip
Al Sweigart al@inventwithpython.com
BSD License
Example Usage
>>> import pyperclip >>> pyperclip.copy('The text to be copied to the clipboard.') >>> pyperclip.paste() 'The text to be copied to the clipboard.'
Currently only handles plaintext.
On Windows, no additional modules are needed.
On Mac, this module makes use of the pbcopy and pbpaste commands, which should come with the os.
On Linux, this module makes use of the xclip or xsel commands, which should come with the os. Otherwise run “sudo apt-get install xclip” or “sudo apt-get install xsel” (Note: xsel does not always seem to work.)
Otherwise on Linux, you will need the gtk or PyQt4 modules installed.
Download files
Download the file for your platform. If you’re not sure which to choose, learn more about installing packages.
Source Distribution
Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with Python 2 and 3.
Install on Windows: pip install pyperclip
Install on Linux/macOS: pip3 install pyperclip
Al Sweigart al@inventwithpython.com
BSD License
Example Usage
>>> import pyperclip
>>> pyperclip.copy('The text to be copied to the clipboard.')
>>> pyperclip.paste()
'The text to be copied to the clipboard.'
Currently only handles plaintext.
On Windows, no additional modules are needed.
On Mac, this module makes use of the pbcopy and pbpaste commands, which should come with the os.
On Linux, this module makes use of the xclip or xsel commands, which should come with the os. Otherwise run «sudo apt-get install xclip» or «sudo apt-get install xsel» (Note: xsel does not always seem to work.)
Otherwise on Linux, you will need the gtk or PyQt4 modules installed.
Support
If you find this project helpful and would like to support its development, consider donating to its creator on Patreon.
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.
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
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.
.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()
.waitForPaste waits for some plain text in the clipboard. It blocks and doesn’t return anything until it detects some text in the clipboard.
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()
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()
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)
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())
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.
Trending Python Articles
-
[Fixed] Module Seaborn has no Attribute Histplot Error
●January 18, 2023
-
Thonny: Text Wrapping Made Easy
by Rahul Kumar Yadav●January 18, 2023
-
[Fixed] JavaScript error: IPython is Not Defined
by Rahul Kumar Yadav●January 18, 2023
-
[Fixed] “io.unsupportedoperation not readable” Error
by Rahul Kumar Yadav●January 18, 2023
- HowTo
- Python How-To’s
- Install Pyperclip in Python
- Install
pyperclip
With thepip
Package Manager in Python - Manually Install the
pyperclip
Module in Python
This tutorial will discuss the methods to install pyperclip
in Python.
Install pyperclip
With the pip
Package Manager in Python
The pyperclip
module is a cross-platform Python module that provides clipboard functionality. The pip
package manager can be used to install pyperclip
. The following command shows us how we can install the pyperclip
module in Python.
To install, open the command prompt and paste the command mentioned above into it.
The following command is used to check whether pyperclip
is properly installed on our machine or not.
The command mentioned above lists all the python packages installed on our machine.
We can also install the pyperclip
module with the pip3
package manager, similar to our previous command.
Note that we cannot use libraries like tkinter
and pyperclip
in the Jupyter Notebook.
Manually Install the pyperclip
Module in Python
Follow the following steps below to install the pyperclip
module in Python manually.
-
Manually download the
pyperclip
from the following this link. -
Try importing the
pyperclip
module in your Python code file.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
Related Article — Python Module
Improve Article
Save Article
Improve Article
Save Article
Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with both Python 2 and 3. This module was created to enable cross-platform copy-pasting in Python which was earlier absent. The pyperclip
module has copy()
and paste()
functions that can send text to and receive text from your computer’s clipboard. Sending the output of your program to the clipboard will make it easy to paste it on an email, word processor, or some other software.
Installing pyperclip:
pip install pyperclip
To copy text to the clipboard, pass a string to pyperclip.copy()
. To paste the text from the clipboard, call pyperclip.paste()
and the text will be returned as a string value.
Code 1:
import
pyperclip as pc
text1
=
"GeeksforGeeks"
pc.copy(text1)
text2
=
pc.paste()
print
(text2)
Output :
GeeksforGeeks
Code 2:
import
pyperclip as pc
number
=
100
pc.copy(number)
text
=
pc.paste()
print
(text)
print
(
type
(text))
Output :
100
Note : Copy function will convert every data type to string.
Improve Article
Save Article
Improve Article
Save Article
Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with both Python 2 and 3. This module was created to enable cross-platform copy-pasting in Python which was earlier absent. The pyperclip
module has copy()
and paste()
functions that can send text to and receive text from your computer’s clipboard. Sending the output of your program to the clipboard will make it easy to paste it on an email, word processor, or some other software.
Installing pyperclip:
pip install pyperclip
To copy text to the clipboard, pass a string to pyperclip.copy()
. To paste the text from the clipboard, call pyperclip.paste()
and the text will be returned as a string value.
Code 1:
import
pyperclip as pc
text1
=
"GeeksforGeeks"
pc.copy(text1)
text2
=
pc.paste()
print
(text2)
Output :
GeeksforGeeks
Code 2:
import
pyperclip as pc
number
=
100
pc.copy(number)
text
=
pc.paste()
print
(text)
print
(
type
(text))
Output :
100
Note : Copy function will convert every data type to string.
Pyperclip – это небольшой кроссплатформенный (Windows, Linux, OS X) модуль для копирования и вставки текста в буфер обмена, разработанный Элом Свейгартом. Он работает на Python 2 и 3 и устанавливается с помощью pip:
pip install pyperclip
Содержание
- 1 Функционал
- 2 Пример
Функционал
В системах Microsoft Windows дополнительный пакет не требуется, поскольку он взаимодействует непосредственно с Windows API через модуль ctypes.
В дистрибутивах Linux модуль использует одну из следующих программ: xclip и xsel. Если какие-либо из них не установлены по умолчанию, их можно получить, выполнив команду:
Code language: JavaScript (javascript)
sudo apt-get install xclip sudo apt-get install xsel
Если таковых нет, pyperclip может использовать функции Qt (PyQt 4) или GTK (недоступно в Python 3), если они установлены.
В Mac OS X для этого используются pbcopy и pbpaste.
Пример
Code language: PHP (php)
>>> import pyperclip as clipboard # Копирование текста в буфер обмена. >>> clipboard.copy("Текст для копирования") # Получить доступ к содержимому (вставить). >>> clipboard.paste() 'Текст для копирования'