I have made a program which monitors the keyboard and writes all pressed keys in the document, but to save changes it have to be close, how i can update information without closing? I am using lib "pynput"
I have tried to make a loop for opening and closing doccument but it hasn't worked corectly.
#input the lib
from pynput import keyboard
file = open("test.txt", "a")
def on_press(key):
'''check pressed keys, AttributeError is for special keys'''
try:
file.write(key.char)
except AttributeError:
file.write('{0}'.format(key))
def on_release(key):
'''if that keys pressed go to a new line, if esc than stop a program and save changes'''
if key == keyboard.Key.space:
file.write("\n")
if key == keyboard.Key.enter:
file.write("\n")
if key == keyboard.Key.esc:
file.write("\n")
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
file.close()
I want it to save changes in a real time.