2013-01-22 68 views
0

我正在創建一個python腳本來記錄我按下我的系統(鍵盤記錄)的密鑰,並用我的打字習慣。我是python的新手,我正在使用這個應用程序來了解它。我使用python-3.x和Windows 8python崩潰pyHook.HookManager()on KeyDown [ctrl] + [c]

完整的源代碼可以在這裏 https://github.com/funvill/QSMonitor/blob/master/monitor.py

發現使用這個片段,我能記錄在我的整個系統中的所有按鍵。問題是當我[ctrl] + [c]在python代碼崩潰的另一個窗口中複製某些內容時。

步驟來重現

  1. 運行monitor.py腳本
  2. 在另一個窗口(記事本),鍵入幾個字母(ABCD)。
  3. 突出顯示在記事本中的字母,然後按住[Ctrl]鍵後按[C]

經驗:

的Windows錯誤信息會彈出,告訴我,python.exe已停止運作,並需要重新啓動。在命令窗口中沒有python錯誤消息。

def OnKeyboardEvent(event): 
    global keyDatabase 
    global keyLoggerCount 
    keyLoggerCount += 1 

    # http://code.activestate.com/recipes/553270-using-pyhook-to-block-windows-keys/ 
    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 ('---')  

    # check to see if this key has ever been pressed before 
    # if it has not then add it and set its start value to zero. 
    if event.Key not in keyDatabase: 
     keyDatabase[ event.Key ] = 0 ; 

    # Incurment the key value 
    keyDatabase[ event.Key ] += 1 ; 
    return True 

# When the user presses a key down anywhere on their system 
# the hook manager will call OnKeyboardEvent function.  
hm = pyHook.HookManager() 
hm.KeyDown = OnKeyboardEvent 
hm.HookKeyboard() 

while True : 
    pythoncom.PumpWaitingMessages() 

我的問題是:

  • 什麼引起的副本,和過去的這個崩潰?

回答

1

如果你想趕上KeyboardInterrupt例外,你可以使用一個嵌套循環。這種方式發生KeyboardInterrupt時,程序僅退出內部循環。

while True: 
    try: 
     while True: 
      pythoncom.PumpWaitingMessages() 
    except KeyboardInterrupt: 
     pass