title: How to fix this script so that it won't peg the CPU?
body: <p>On my home Kubuntu machine, I am running a script to beep on every keypress, no matter which window or application has focus, adapted from <a href="http://rants.sayanriju.co.cc/script-to-make-tick-tick-sound-on-keypress" rel="noreferrer">this insightful page</a></p>
  
  <pre><code>#!/usr/bin/env python 
  
  from Xlib.display import Display
  import os
  import sys
  
  ZERO=[]
  for i in range(0,32):
          ZERO.append(0)
  ignorelist=[ZERO]
  
  def main():    
          if os.getuid()==0:
                  os.system("modprobe pcspkr")
                  print("Speaker enabled, start as normal user")
                  sys.exit()
  
          print("If no beep is heard, then run as root to enable pcspkr")
  
          disp = Display()
          while 1:
                  keymap=disp.query_keymap()
                  if keymap not in ignorelist:
                          os.system("beep")
  
  if __name__ == '__main__':
          main()
  </code></pre>
  
  <p>The script works great, but it pegs both CPUs of my dual-core Intel machine at around 80% each, so I can do little else with the machine. How can I reduce the CPU requirements of this simple script without interfering with its operation? In other words, it should still beep at the moment of keypress, no matter what window or application has focus.</p>
  
  <p>If this is not possible in Python, what other technologies should I look at? C? I would assume that there exists some kernel component which notifies applications of keypresses: how else does KDE handle global shortcuts? How can I get my application to receive these notices as well?</p>
  
  <p><strong>The goal is to make a beep at the moment each key is pressed</strong>, as I am training my fingers to type on a mechanical keyboard without bottoming out yet without missing keypresses. I just graduated from Cherry Browns to Cherry Blues and the lack of tactical feedback takes some time to get used to.</p>
  
  <p><strong>Note that any solution must emit a beep no matter which window has focus. This program is intended to be used as a daemon that will run in the background of all applications that I use.</strong></p>
  
  <p>Thanks.</p>