I want to run a simple python script in the background that reads text from the clipboard and prints it out. Here is my code.
#!/usr/bin/env python
import Tkinter
last_clipboard = ""
def get_clipboard():
global last_clipboard
root = Tkinter.Tk()
root.withdraw() # Hide the main window (optional)
text_in_clipboard = root.clipboard_get()
if text_in_clipboard != last_clipboard:
last_clipboard = text_in_clipboard
print last_clipboard
while True:
get_clipboard()
This is working as expected but it consumes too much CPU (100% CPU).
How can I make it work correctly without consuming that much?
You forgot the
time.sleep()
in yourwhile
loop, according to this answer on SO sleeping for 0.2s is a good compromise between polling frequency and CPU load:Checking the clipboard every 0.2 seconds seems easily often enough; if you want less CPU load you can even increase this value – few users change the clipboard content from one second to another.
Note that in general polling in a loop as often as that is not considered good design. A better approach would be to act on the event of changing the clipboard content, an example for GTK can be found in this SO answer.
Further reading
time.sleep()
time.sleep()
I finally make it work a without loop. This is the code:
I had to install few modules:
sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0
feel free to choose the solution that fits for you.
You are running the thing in a
while True:
loop! That means that the CPU is constantly running your loop. Just add a small pause there and you should see the CPU usage drop precipitously:I was intrigued by this project so wrote a bash script for those more comfortable in that environment:
It does require Xorg's
xclip
package:It's dumping clipboard contents to screen using
cat
command. If you want hard copy instead replacecat
withlp
and specify your printer name, orientation and possibly "fit to page" option.You will see a bit of lag to screen because I choose
sleep 1.0
which would be unnoticeable with a printer and still faster than people can highlight text and use Ctrl+C.If you copy the exact same highlighted text to the clipboard it doesn't trigger a difference. One letter more or less will trigger a response.