Tuesday Tooling: Copy & Paste From the Terminal and Python
Need to copy something from a Bash script or Python? These two tools will do the job.
xclip - Copy / Paste in the Terminal
Many thanks to Alan Pope for the advice!
Thanks Popey pic.twitter.com/6obR09Sthv
— biglesp (@biglesp) August 7, 2020
xclip - command line interface to X selections (clipboard)
Reads from standard in, or from one or more files, and makes the data available as an X selection for pasting into X applications. Prints current X selection to standard out.
To install xclip, open a terminal, here I am using my Ubuntu laptop, and type the following.
sudo apt install xclip
Lets test the command by using echo to print "test" and pipe the output to the xclip command.
echo "test" | xclip -sel clip
Now open an document, editor etc and paste using CTRL+V
or via right click.
So how is this useful?
Xclip will work with the standard output of any command, so if you need to quickly grab a directory listing and paste it into a document, well this is the tool for you.
pyperclip - copy / paste with Python 3
Need to copy something in your Python project? Then need to paste it somewhere? Pyperclip is what you need.
Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with Python 2 and 3.
Created by Al Sweigart, yes that Al Sweigart who writes the Python books that you love.
To install pyperclip, open a terminal / command prompt and type
Ubuntu / Raspberry Pi / Debian
sudo pip3 install pyperclip
Windows
pip.exe install pyperclip
To use pyperclip we shall make a quick demo. It will copy a string into the buffer and we can then use it in any editor / application.
import pyperclip
pyperclip.copy("Hello world!")
Pyperclip can work with strings, integer, float and boolean values.
If you would like to paste the information back into Python then no problem just use pyperclip.paste()
So how is this useful?
I recently wrote a Python script that would format a URL for use with the CMS at work. I wanted this to output the URL directly to the paste buffer, to save me the trouble of pressing buttons. Well this saved me a few clicks per day. :)