Skip to content
Advertisement

Python Get File Length Of Keyboard Buffer

I am coding a text-based game, and I need to read key presses. For various reasons, I’m doing this by reading the keyboard buffer. This is my current code for that:

while True:
    file = open("/dev/input/event3","rb")
    data = file.read(45)
    character = data[42:43].hex()
    press = data[44:45].hex()

The problem is, that the program will wait until it has read 45 bytes. I do not want this, because the program should do other stuff (like recharging mana). So I thought the program could check to see if the file is empty, and if it isn’t, there would have been a new key press and I could read it. So I wrote this code:

while True:
    file = open("/dev/input/event3","rb")
    while True:
        if os.stat("/dev/input/event3").st_size > 0:
            data = file.read(45)
            break
    character = data[42:43].hex()
    press = data[44:45].hex()

But os.stat("dev/input/event3").st_size returned 0. I also tried with os.path.getsize("/dev/input/event3"), but it also returned 0.

I have considered threading as a possible solution, but it is a bit too complicated for me, especially with transferring variables from one thread to another (and Lock() and similar things are beyond my understanding.

So my question is: Why does this happen, and how can I fix it?

Advertisement

Answer

I have found a solution, that uses threads, but not that complicated. Add this function:

def key_listener():
    while True:
        keyboard_buffer = open("/dev/input/event3","rb")
        data = keyboard_buffer.read(45)
        keyboard_buffer.close()
        character = data[42:43].hex()
        press = data[44:45].hex()
        save_file = open(sys.path[0] + "/key.txt", "w")
        save_file.write(character + "n" + press)
        save_file.close()
key_listen_thread = threading.Thread(target=key_listener, daemon=True)
key_listen_thread.start()

To look if a key is being pressed/was pressed:

save_file = open(sys.path[0] + "/key.txt", "r+")
lines = save_file.readlines()
save_file.write("") # Optional, will delete contents of file
save_file.close()
keycode = "21"
press = "01" # 00 = released, 01 = pressed
try:
    if lines[0].replace("n", "") == keycode and lines[1] == press: # Do something
except IndexError:
    pass
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement