Python Clipboard Access on Ubuntu | Generated by AI
To read from the clipboard (pasteboard) in Ubuntu using Python, you can use libraries like pyperclip or interact with system clipboard utilities like xclip or xsel. Below are two common approaches:
Approach 1: Using pyperclip
pyperclip is a cross-platform Python library for accessing the clipboard.
- Install pyperclip:
pip install pyperclip - Python code to read from clipboard:
import pyperclip # Read the contents of the clipboard clipboard_content = pyperclip.paste() print(clipboard_content) - Notes:
- Ensure
xcliporxselis installed on Ubuntu, aspypercliprelies on them:sudo apt update sudo apt install xclip xsel - This method is simple and works across platforms.
- Ensure
Approach 2: Using xclip Directly
If you prefer to interact with the system clipboard directly, you can use xclip.
- Install xclip:
sudo apt update sudo apt install xclip - Python
System: Python code to read from clipboard using xclip:
import subprocess
# Read the contents of the clipboard
process = subprocess.run(['xclip', '-selection', 'clipboard', '-o'], capture_output=True, text=True)
clipboard_content = process.stdout
print(clipboard_content)
- Notes:
- This approach directly calls the
xclipcommand-line tool. - Use
-selection clipboardfor the modern clipboard (Ctrl+C/Ctrl+V) or-selection primaryfor the mouse-selection clipboard. - Ensure
xclipis installed.
- This approach directly calls the
Recommendations
- Use
pyperclipfor simplicity and portability unless you have specific reasons to usexcliporxsel. - Both methods require
xcliporxselto be installed for clipboard access on Ubuntu. - If the clipboard content is not text (e.g., an image), these methods may not work as expected, and you’d need a library like
pyclipor additional handling for non-text data.
Tested on Ubuntu 22.04 with Python 3.10. If you encounter issues, ensure the required tools (xclip or xsel) are installed and the clipboard contains text data.