我正在创建一个python脚本来记录我在系统中按下的键(键盘记录器),然后打电话给家里,提供有关我的打字习惯的信息。我是python的新手,我正在使用这个应用程序来了解它。我正在使用python-3.x和windows 8
可以在此处找到完整的源代码 https://github.com/funvill/QSMonitor/blob/master/monitor.py
使用此代码段,我可以记录整个系统中的所有按键。问题是当我[ctrl] + [c]在另一个窗口中复制某些内容时,python代码崩溃了。
重现的步骤
有经验:
将弹出一条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()
我的问题是:
答案 0 :(得分:1)
在python中,Ctrl + C会抛出KeyboardInterrupt异常。
http://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt
答案 1 :(得分:1)
如果要捕获KeyboardInterrupt
个异常,可以使用嵌套循环。这样,当KEYInterrupt发生时,程序只退出内部循环。
while True:
try:
while True:
pythoncom.PumpWaitingMessages()
except KeyboardInterrupt:
pass