pyperclip
Pyperclip is a cross-platform Python module (current version 1.11.0) for copying and pasting plain text to and from the clipboard. It provides a simple API (`copy()` and `paste()`) and is actively maintained with regular updates, enabling clipboard interaction across Windows, macOS, and Linux.
Warnings
- gotcha On Linux, `pyperclip` may raise a 'Pyperclip could not find a copy/paste mechanism' error. This typically means required command-line utilities (like `xclip`, `xsel`, or `wl-clipboard`) or Python modules (like `PyQt5`, `PyQt4`, or `gtk`) are not installed.
- gotcha Pyperclip only handles plain text. If you copy images or rich text, `pyperclip.paste()` will return an empty string or plain text representation if available.
- gotcha When running `pyperclip` in a remote server environment (e.g., Streamlit Cloud, Docker containers, WSL2), it interacts with the *server's* clipboard, not the client's local clipboard. This can lead to unexpected behavior or `FileNotFoundError` (e.g., `clip.exe` not found).
- breaking Recent versions (1.9.0, 1.10.0, 1.11.0) have dropped or broken Python 2 compatibility due to updated dependencies or syntax. The library is now primarily Python 3 focused.
- gotcha When copying text from files or other sources, ensure to strip any unintended line breaks (e.g., `\n`, `\r`) before passing to `pyperclip.copy()`. Including these can lead to incorrectly formatted paths or text when pasted into other applications.
- gotcha The `pyperclip.paste()` function does not take any arguments. Passing an argument to `paste()` (e.g., `pyperclip.paste('some text')`) will result in a `TypeError`.
Install
-
pip install pyperclip
Imports
- pyperclip
import pyperclip
Quickstart
import pyperclip
text_to_copy = 'Hello, world! This is copied by pyperclip.'
pyperclip.copy(text_to_copy)
print(f'Copied: "{text_to_copy}" to clipboard.')
pasted_text = pyperclip.paste()
print(f'Pasted: "{pasted_text}" from clipboard.')
# Example of waiting for new paste (requires manual paste action by user)
# print('Waiting for a new paste (max 5 seconds)...')
# try:
# new_paste = pyperclip.waitForNewPaste(timeout=5)
# print(f'New text pasted: "{new_paste}"')
# except pyperclip.PyperclipTimeoutException:
# print('No new paste detected within 5 seconds.')