Why is this python script running in background consuming 100 % CPU?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







22















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?










share|improve this question




















  • 26





    If at all supported by the framework you're using, use event-based code to detect changes in the clipboard rather than a loop. There's a difference between getting the clipboard continuously until it changes or to listen to the system telling you that it changed.

    – stefan
    May 17 at 11:16






  • 6





    @dessert I haven't ever done it in python, but here seems to be a solution with GTK: stackoverflow.com/a/25961646/985296 (doesn't mention any platform dependency).

    – stefan
    May 17 at 11:39











  • @jpmc26 & dessert Looks like a meta discussion, feel free to take it up there. Definitely a good idea to get this cleared up for scope.

    – Mast
    May 19 at 14:45






  • 1





    @dessert Open a meta thread if you and JPMC want to discuss whether this is on/off topic. Please do not use comments for this argument. (Comment cleanup complete, topic locked for a week pending your Meta discussion but to also stop the comment argument)

    – Thomas Ward
    May 21 at 16:06


















22















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?










share|improve this question




















  • 26





    If at all supported by the framework you're using, use event-based code to detect changes in the clipboard rather than a loop. There's a difference between getting the clipboard continuously until it changes or to listen to the system telling you that it changed.

    – stefan
    May 17 at 11:16






  • 6





    @dessert I haven't ever done it in python, but here seems to be a solution with GTK: stackoverflow.com/a/25961646/985296 (doesn't mention any platform dependency).

    – stefan
    May 17 at 11:39











  • @jpmc26 & dessert Looks like a meta discussion, feel free to take it up there. Definitely a good idea to get this cleared up for scope.

    – Mast
    May 19 at 14:45






  • 1





    @dessert Open a meta thread if you and JPMC want to discuss whether this is on/off topic. Please do not use comments for this argument. (Comment cleanup complete, topic locked for a week pending your Meta discussion but to also stop the comment argument)

    – Thomas Ward
    May 21 at 16:06














22












22








22


4






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?










share|improve this question
















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?







scripts python clipboard






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 18 at 16:53









Zanna

52.1k13144246




52.1k13144246










asked May 17 at 8:43









dmxdmx

96521124




96521124








  • 26





    If at all supported by the framework you're using, use event-based code to detect changes in the clipboard rather than a loop. There's a difference between getting the clipboard continuously until it changes or to listen to the system telling you that it changed.

    – stefan
    May 17 at 11:16






  • 6





    @dessert I haven't ever done it in python, but here seems to be a solution with GTK: stackoverflow.com/a/25961646/985296 (doesn't mention any platform dependency).

    – stefan
    May 17 at 11:39











  • @jpmc26 & dessert Looks like a meta discussion, feel free to take it up there. Definitely a good idea to get this cleared up for scope.

    – Mast
    May 19 at 14:45






  • 1





    @dessert Open a meta thread if you and JPMC want to discuss whether this is on/off topic. Please do not use comments for this argument. (Comment cleanup complete, topic locked for a week pending your Meta discussion but to also stop the comment argument)

    – Thomas Ward
    May 21 at 16:06














  • 26





    If at all supported by the framework you're using, use event-based code to detect changes in the clipboard rather than a loop. There's a difference between getting the clipboard continuously until it changes or to listen to the system telling you that it changed.

    – stefan
    May 17 at 11:16






  • 6





    @dessert I haven't ever done it in python, but here seems to be a solution with GTK: stackoverflow.com/a/25961646/985296 (doesn't mention any platform dependency).

    – stefan
    May 17 at 11:39











  • @jpmc26 & dessert Looks like a meta discussion, feel free to take it up there. Definitely a good idea to get this cleared up for scope.

    – Mast
    May 19 at 14:45






  • 1





    @dessert Open a meta thread if you and JPMC want to discuss whether this is on/off topic. Please do not use comments for this argument. (Comment cleanup complete, topic locked for a week pending your Meta discussion but to also stop the comment argument)

    – Thomas Ward
    May 21 at 16:06








26




26





If at all supported by the framework you're using, use event-based code to detect changes in the clipboard rather than a loop. There's a difference between getting the clipboard continuously until it changes or to listen to the system telling you that it changed.

– stefan
May 17 at 11:16





If at all supported by the framework you're using, use event-based code to detect changes in the clipboard rather than a loop. There's a difference between getting the clipboard continuously until it changes or to listen to the system telling you that it changed.

– stefan
May 17 at 11:16




6




6





@dessert I haven't ever done it in python, but here seems to be a solution with GTK: stackoverflow.com/a/25961646/985296 (doesn't mention any platform dependency).

– stefan
May 17 at 11:39





@dessert I haven't ever done it in python, but here seems to be a solution with GTK: stackoverflow.com/a/25961646/985296 (doesn't mention any platform dependency).

– stefan
May 17 at 11:39













@jpmc26 & dessert Looks like a meta discussion, feel free to take it up there. Definitely a good idea to get this cleared up for scope.

– Mast
May 19 at 14:45





@jpmc26 & dessert Looks like a meta discussion, feel free to take it up there. Definitely a good idea to get this cleared up for scope.

– Mast
May 19 at 14:45




1




1





@dessert Open a meta thread if you and JPMC want to discuss whether this is on/off topic. Please do not use comments for this argument. (Comment cleanup complete, topic locked for a week pending your Meta discussion but to also stop the comment argument)

– Thomas Ward
May 21 at 16:06





@dessert Open a meta thread if you and JPMC want to discuss whether this is on/off topic. Please do not use comments for this argument. (Comment cleanup complete, topic locked for a week pending your Meta discussion but to also stop the comment argument)

– Thomas Ward
May 21 at 16:06










4 Answers
4






active

oldest

votes


















44














You forgot the time.sleep() in your while loop, according to this answer on SO sleeping for 0.2s is a good compromise between polling frequency and CPU load:



import time

while True:
get_clipboard()
time.sleep(0.2) # sleep for 0.2 seconds


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




  • linuxconfig.org article on Python While Loops

  • cyberciti.biz article on time.sleep()


  • blog article on How To Make Python Wait discussing different ways, some of which are much more elaborate and flexible than the static time.sleep()






share|improve this answer





















  • 3





    You could make the sleep interval shorter without really affecting the CPU time used. I found on my Mac: 0.01 s: 69%, 0.02 s: 43%, 0.05 s: 25%, 0.1 s: 14%, 0.2 s: 7%. 0.5 s: 3%

    – Floris
    May 17 at 14:33






  • 6





    Polling still sucks because it keeps waking up this process polluting CPU caches and so on. As discussed in comments much better to wait for notification of a clipboard change.

    – Peter Cordes
    May 17 at 16:13











  • @dessert: If I knew the answer, I would. I merely suggest mentioning in your answer that waking up every 0.2 seconds is still not considered a good design, and looking for a non-polling approach would be much better. But for a one-off hack that is only going to run on one computer, sure it's not horrible, and is probably good enough.

    – Peter Cordes
    May 17 at 16:56



















26














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



#!/usr/bin/env python3
import gi, sys
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

last_clipboard = ""

def callBack(*args):
global last_clipboard
new_clipboard = clip.wait_for_text()
if new_clipboard != last_clipboard:
last_clipboard = new_clipboard
print("new Clipboard")
print(new_clipboard)

clip = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clip.connect('owner-change',callBack)
Gtk.main()


feel free to choose the solution that fits for you.






share|improve this answer


























  • Oooh… Why are you requesting clip.wait_for_text() twice?

    – wizzwizz4
    May 19 at 15:52











  • @wizzwizz4 you are right I edited ... tanks

    – dmx
    May 19 at 16:27











  • @wizzwizz4 Doesn't everyone copy twice just to be sure?

    – Michael Frank
    May 20 at 7:53





















16














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:



#!/usr/bin/env python

import Tkinter
import time

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()
time.sleep(1)





share|improve this answer































    3














    I was intrigued by this project so wrote a bash script for those more comfortable in that environment:



    #!/bin/bash

    xclip -o -sel clip > /tmp/LastClip

    while true ; do

    xclip -o -sel clip > /tmp/NewClip
    diff -q /tmp/LastClip /tmp/NewClip > /tmp/DiffClip
    if [[ -s /tmp/DiffClip ]] ; then
    cat /tmp/NewClip # For testing dump to screen instead of printing
    cp -a /tmp/NewClip /tmp/LastClip
    fi
    sleep 1.0

    done


    It does require Xorg's xclip package:



    sudo apt install xclip


    It's dumping clipboard contents to screen using cat command. If you want hard copy instead replace cat with lp 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.






    share|improve this answer
























      Your Answer








      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "89"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1143959%2fwhy-is-this-python-script-running-in-background-consuming-100-cpu%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      44














      You forgot the time.sleep() in your while loop, according to this answer on SO sleeping for 0.2s is a good compromise between polling frequency and CPU load:



      import time

      while True:
      get_clipboard()
      time.sleep(0.2) # sleep for 0.2 seconds


      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




      • linuxconfig.org article on Python While Loops

      • cyberciti.biz article on time.sleep()


      • blog article on How To Make Python Wait discussing different ways, some of which are much more elaborate and flexible than the static time.sleep()






      share|improve this answer





















      • 3





        You could make the sleep interval shorter without really affecting the CPU time used. I found on my Mac: 0.01 s: 69%, 0.02 s: 43%, 0.05 s: 25%, 0.1 s: 14%, 0.2 s: 7%. 0.5 s: 3%

        – Floris
        May 17 at 14:33






      • 6





        Polling still sucks because it keeps waking up this process polluting CPU caches and so on. As discussed in comments much better to wait for notification of a clipboard change.

        – Peter Cordes
        May 17 at 16:13











      • @dessert: If I knew the answer, I would. I merely suggest mentioning in your answer that waking up every 0.2 seconds is still not considered a good design, and looking for a non-polling approach would be much better. But for a one-off hack that is only going to run on one computer, sure it's not horrible, and is probably good enough.

        – Peter Cordes
        May 17 at 16:56
















      44














      You forgot the time.sleep() in your while loop, according to this answer on SO sleeping for 0.2s is a good compromise between polling frequency and CPU load:



      import time

      while True:
      get_clipboard()
      time.sleep(0.2) # sleep for 0.2 seconds


      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




      • linuxconfig.org article on Python While Loops

      • cyberciti.biz article on time.sleep()


      • blog article on How To Make Python Wait discussing different ways, some of which are much more elaborate and flexible than the static time.sleep()






      share|improve this answer





















      • 3





        You could make the sleep interval shorter without really affecting the CPU time used. I found on my Mac: 0.01 s: 69%, 0.02 s: 43%, 0.05 s: 25%, 0.1 s: 14%, 0.2 s: 7%. 0.5 s: 3%

        – Floris
        May 17 at 14:33






      • 6





        Polling still sucks because it keeps waking up this process polluting CPU caches and so on. As discussed in comments much better to wait for notification of a clipboard change.

        – Peter Cordes
        May 17 at 16:13











      • @dessert: If I knew the answer, I would. I merely suggest mentioning in your answer that waking up every 0.2 seconds is still not considered a good design, and looking for a non-polling approach would be much better. But for a one-off hack that is only going to run on one computer, sure it's not horrible, and is probably good enough.

        – Peter Cordes
        May 17 at 16:56














      44












      44








      44







      You forgot the time.sleep() in your while loop, according to this answer on SO sleeping for 0.2s is a good compromise between polling frequency and CPU load:



      import time

      while True:
      get_clipboard()
      time.sleep(0.2) # sleep for 0.2 seconds


      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




      • linuxconfig.org article on Python While Loops

      • cyberciti.biz article on time.sleep()


      • blog article on How To Make Python Wait discussing different ways, some of which are much more elaborate and flexible than the static time.sleep()






      share|improve this answer















      You forgot the time.sleep() in your while loop, according to this answer on SO sleeping for 0.2s is a good compromise between polling frequency and CPU load:



      import time

      while True:
      get_clipboard()
      time.sleep(0.2) # sleep for 0.2 seconds


      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




      • linuxconfig.org article on Python While Loops

      • cyberciti.biz article on time.sleep()


      • blog article on How To Make Python Wait discussing different ways, some of which are much more elaborate and flexible than the static time.sleep()







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited May 18 at 16:52









      Zanna

      52.1k13144246




      52.1k13144246










      answered May 17 at 8:51









      dessertdessert

      27.5k682115




      27.5k682115








      • 3





        You could make the sleep interval shorter without really affecting the CPU time used. I found on my Mac: 0.01 s: 69%, 0.02 s: 43%, 0.05 s: 25%, 0.1 s: 14%, 0.2 s: 7%. 0.5 s: 3%

        – Floris
        May 17 at 14:33






      • 6





        Polling still sucks because it keeps waking up this process polluting CPU caches and so on. As discussed in comments much better to wait for notification of a clipboard change.

        – Peter Cordes
        May 17 at 16:13











      • @dessert: If I knew the answer, I would. I merely suggest mentioning in your answer that waking up every 0.2 seconds is still not considered a good design, and looking for a non-polling approach would be much better. But for a one-off hack that is only going to run on one computer, sure it's not horrible, and is probably good enough.

        – Peter Cordes
        May 17 at 16:56














      • 3





        You could make the sleep interval shorter without really affecting the CPU time used. I found on my Mac: 0.01 s: 69%, 0.02 s: 43%, 0.05 s: 25%, 0.1 s: 14%, 0.2 s: 7%. 0.5 s: 3%

        – Floris
        May 17 at 14:33






      • 6





        Polling still sucks because it keeps waking up this process polluting CPU caches and so on. As discussed in comments much better to wait for notification of a clipboard change.

        – Peter Cordes
        May 17 at 16:13











      • @dessert: If I knew the answer, I would. I merely suggest mentioning in your answer that waking up every 0.2 seconds is still not considered a good design, and looking for a non-polling approach would be much better. But for a one-off hack that is only going to run on one computer, sure it's not horrible, and is probably good enough.

        – Peter Cordes
        May 17 at 16:56








      3




      3





      You could make the sleep interval shorter without really affecting the CPU time used. I found on my Mac: 0.01 s: 69%, 0.02 s: 43%, 0.05 s: 25%, 0.1 s: 14%, 0.2 s: 7%. 0.5 s: 3%

      – Floris
      May 17 at 14:33





      You could make the sleep interval shorter without really affecting the CPU time used. I found on my Mac: 0.01 s: 69%, 0.02 s: 43%, 0.05 s: 25%, 0.1 s: 14%, 0.2 s: 7%. 0.5 s: 3%

      – Floris
      May 17 at 14:33




      6




      6





      Polling still sucks because it keeps waking up this process polluting CPU caches and so on. As discussed in comments much better to wait for notification of a clipboard change.

      – Peter Cordes
      May 17 at 16:13





      Polling still sucks because it keeps waking up this process polluting CPU caches and so on. As discussed in comments much better to wait for notification of a clipboard change.

      – Peter Cordes
      May 17 at 16:13













      @dessert: If I knew the answer, I would. I merely suggest mentioning in your answer that waking up every 0.2 seconds is still not considered a good design, and looking for a non-polling approach would be much better. But for a one-off hack that is only going to run on one computer, sure it's not horrible, and is probably good enough.

      – Peter Cordes
      May 17 at 16:56





      @dessert: If I knew the answer, I would. I merely suggest mentioning in your answer that waking up every 0.2 seconds is still not considered a good design, and looking for a non-polling approach would be much better. But for a one-off hack that is only going to run on one computer, sure it's not horrible, and is probably good enough.

      – Peter Cordes
      May 17 at 16:56













      26














      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



      #!/usr/bin/env python3
      import gi, sys
      gi.require_version('Gtk', '3.0')
      from gi.repository import Gtk, Gdk

      last_clipboard = ""

      def callBack(*args):
      global last_clipboard
      new_clipboard = clip.wait_for_text()
      if new_clipboard != last_clipboard:
      last_clipboard = new_clipboard
      print("new Clipboard")
      print(new_clipboard)

      clip = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
      clip.connect('owner-change',callBack)
      Gtk.main()


      feel free to choose the solution that fits for you.






      share|improve this answer


























      • Oooh… Why are you requesting clip.wait_for_text() twice?

        – wizzwizz4
        May 19 at 15:52











      • @wizzwizz4 you are right I edited ... tanks

        – dmx
        May 19 at 16:27











      • @wizzwizz4 Doesn't everyone copy twice just to be sure?

        – Michael Frank
        May 20 at 7:53


















      26














      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



      #!/usr/bin/env python3
      import gi, sys
      gi.require_version('Gtk', '3.0')
      from gi.repository import Gtk, Gdk

      last_clipboard = ""

      def callBack(*args):
      global last_clipboard
      new_clipboard = clip.wait_for_text()
      if new_clipboard != last_clipboard:
      last_clipboard = new_clipboard
      print("new Clipboard")
      print(new_clipboard)

      clip = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
      clip.connect('owner-change',callBack)
      Gtk.main()


      feel free to choose the solution that fits for you.






      share|improve this answer


























      • Oooh… Why are you requesting clip.wait_for_text() twice?

        – wizzwizz4
        May 19 at 15:52











      • @wizzwizz4 you are right I edited ... tanks

        – dmx
        May 19 at 16:27











      • @wizzwizz4 Doesn't everyone copy twice just to be sure?

        – Michael Frank
        May 20 at 7:53
















      26












      26








      26







      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



      #!/usr/bin/env python3
      import gi, sys
      gi.require_version('Gtk', '3.0')
      from gi.repository import Gtk, Gdk

      last_clipboard = ""

      def callBack(*args):
      global last_clipboard
      new_clipboard = clip.wait_for_text()
      if new_clipboard != last_clipboard:
      last_clipboard = new_clipboard
      print("new Clipboard")
      print(new_clipboard)

      clip = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
      clip.connect('owner-change',callBack)
      Gtk.main()


      feel free to choose the solution that fits for you.






      share|improve this answer















      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



      #!/usr/bin/env python3
      import gi, sys
      gi.require_version('Gtk', '3.0')
      from gi.repository import Gtk, Gdk

      last_clipboard = ""

      def callBack(*args):
      global last_clipboard
      new_clipboard = clip.wait_for_text()
      if new_clipboard != last_clipboard:
      last_clipboard = new_clipboard
      print("new Clipboard")
      print(new_clipboard)

      clip = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
      clip.connect('owner-change',callBack)
      Gtk.main()


      feel free to choose the solution that fits for you.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited May 19 at 16:26

























      answered May 18 at 8:27









      dmxdmx

      96521124




      96521124













      • Oooh… Why are you requesting clip.wait_for_text() twice?

        – wizzwizz4
        May 19 at 15:52











      • @wizzwizz4 you are right I edited ... tanks

        – dmx
        May 19 at 16:27











      • @wizzwizz4 Doesn't everyone copy twice just to be sure?

        – Michael Frank
        May 20 at 7:53





















      • Oooh… Why are you requesting clip.wait_for_text() twice?

        – wizzwizz4
        May 19 at 15:52











      • @wizzwizz4 you are right I edited ... tanks

        – dmx
        May 19 at 16:27











      • @wizzwizz4 Doesn't everyone copy twice just to be sure?

        – Michael Frank
        May 20 at 7:53



















      Oooh… Why are you requesting clip.wait_for_text() twice?

      – wizzwizz4
      May 19 at 15:52





      Oooh… Why are you requesting clip.wait_for_text() twice?

      – wizzwizz4
      May 19 at 15:52













      @wizzwizz4 you are right I edited ... tanks

      – dmx
      May 19 at 16:27





      @wizzwizz4 you are right I edited ... tanks

      – dmx
      May 19 at 16:27













      @wizzwizz4 Doesn't everyone copy twice just to be sure?

      – Michael Frank
      May 20 at 7:53







      @wizzwizz4 Doesn't everyone copy twice just to be sure?

      – Michael Frank
      May 20 at 7:53













      16














      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:



      #!/usr/bin/env python

      import Tkinter
      import time

      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()
      time.sleep(1)





      share|improve this answer




























        16














        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:



        #!/usr/bin/env python

        import Tkinter
        import time

        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()
        time.sleep(1)





        share|improve this answer


























          16












          16








          16







          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:



          #!/usr/bin/env python

          import Tkinter
          import time

          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()
          time.sleep(1)





          share|improve this answer













          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:



          #!/usr/bin/env python

          import Tkinter
          import time

          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()
          time.sleep(1)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered May 17 at 8:51









          terdonterdon

          70.6k13147231




          70.6k13147231























              3














              I was intrigued by this project so wrote a bash script for those more comfortable in that environment:



              #!/bin/bash

              xclip -o -sel clip > /tmp/LastClip

              while true ; do

              xclip -o -sel clip > /tmp/NewClip
              diff -q /tmp/LastClip /tmp/NewClip > /tmp/DiffClip
              if [[ -s /tmp/DiffClip ]] ; then
              cat /tmp/NewClip # For testing dump to screen instead of printing
              cp -a /tmp/NewClip /tmp/LastClip
              fi
              sleep 1.0

              done


              It does require Xorg's xclip package:



              sudo apt install xclip


              It's dumping clipboard contents to screen using cat command. If you want hard copy instead replace cat with lp 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.






              share|improve this answer




























                3














                I was intrigued by this project so wrote a bash script for those more comfortable in that environment:



                #!/bin/bash

                xclip -o -sel clip > /tmp/LastClip

                while true ; do

                xclip -o -sel clip > /tmp/NewClip
                diff -q /tmp/LastClip /tmp/NewClip > /tmp/DiffClip
                if [[ -s /tmp/DiffClip ]] ; then
                cat /tmp/NewClip # For testing dump to screen instead of printing
                cp -a /tmp/NewClip /tmp/LastClip
                fi
                sleep 1.0

                done


                It does require Xorg's xclip package:



                sudo apt install xclip


                It's dumping clipboard contents to screen using cat command. If you want hard copy instead replace cat with lp 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.






                share|improve this answer


























                  3












                  3








                  3







                  I was intrigued by this project so wrote a bash script for those more comfortable in that environment:



                  #!/bin/bash

                  xclip -o -sel clip > /tmp/LastClip

                  while true ; do

                  xclip -o -sel clip > /tmp/NewClip
                  diff -q /tmp/LastClip /tmp/NewClip > /tmp/DiffClip
                  if [[ -s /tmp/DiffClip ]] ; then
                  cat /tmp/NewClip # For testing dump to screen instead of printing
                  cp -a /tmp/NewClip /tmp/LastClip
                  fi
                  sleep 1.0

                  done


                  It does require Xorg's xclip package:



                  sudo apt install xclip


                  It's dumping clipboard contents to screen using cat command. If you want hard copy instead replace cat with lp 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.






                  share|improve this answer













                  I was intrigued by this project so wrote a bash script for those more comfortable in that environment:



                  #!/bin/bash

                  xclip -o -sel clip > /tmp/LastClip

                  while true ; do

                  xclip -o -sel clip > /tmp/NewClip
                  diff -q /tmp/LastClip /tmp/NewClip > /tmp/DiffClip
                  if [[ -s /tmp/DiffClip ]] ; then
                  cat /tmp/NewClip # For testing dump to screen instead of printing
                  cp -a /tmp/NewClip /tmp/LastClip
                  fi
                  sleep 1.0

                  done


                  It does require Xorg's xclip package:



                  sudo apt install xclip


                  It's dumping clipboard contents to screen using cat command. If you want hard copy instead replace cat with lp 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.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered May 18 at 23:26









                  WinEunuuchs2UnixWinEunuuchs2Unix

                  51.5k13101200




                  51.5k13101200






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Ask Ubuntu!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1143959%2fwhy-is-this-python-script-running-in-background-consuming-100-cpu%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

                      Bunad

                      Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum