views:

81

answers:

3

Hi, I have a timer, and need to know if any of the keys is pressed on any cycle. How do I do it?

A: 

Try:

import sys
c = sys.stdin.read(1)
motto
Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> c = sys.stdin.read(1)AttributeError: readAlso, i need a way to get information about keys pressed in the whole pc, even if my wx application is in the background.
Gabriele Cirulli
+1  A: 

If you are using Linux it's found in the curses module, if you use Windows it's in the msvcrt module. I found following article really helpful in describing this topic - Event Driven Programming

artdanil
msvcrt.getch() seems to crash my wx application
Gabriele Cirulli
Either post a traceback information or give more detail on what is going on in code. Even using `msvcrt`, you will need to write event handlers and call them from within your timer loop. However, considering your comment about background execution, `msvcrt` should be what you are looking for. You will just need to figure out how to use it in your particular case.
artdanil
there's no traceback, my application just locks up.
Gabriele Cirulli
A: 

If you are using Windows, Use PyHook If you like to know system wide key press events.

import pythoncom, pyHook 

def OnKeyboardEvent(event):
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended

    return True #for pass through key events, False to eat Keys

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
S.Mark