0

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.

dev_Yu
  • 11
  • 5

1 Answers1

0

You can use file.flush() for your specific use-case. You might need to follow up with os.fsync(file.fileno())

As per the documentation, it will "[...] force write of file with filedescriptor fd to disk. On Unix, this calls the native fsync() function; on Windows, the MS _commit() function"

Check out the official documentation, along with some other discussions on this very issue. I've seen this re-asked on StackOverflow, but I opted to respond as it was under the Python-3.x tag, and people can offer Python3-specific hints.

Let me know if this works, and if not, what's your platform

hyperTrashPanda
  • 838
  • 5
  • 18
  • i used this in this way: file.write(key.char) file.flush() os.fsync(file.fileno()) and this works properly. Thank you for help. Forget to told, i work on windows – dev_Yu Feb 10 '19 at 19:15
  • Nice, thanks for reporting it works correctly in Windows as well, I had tested only on Linux! If the answer was satisfactory, feel free to accept it so the question is closed and can be referred by others in the future. – hyperTrashPanda Feb 10 '19 at 21:41