0

The blessed Python library looks great for making console apps, but I'm having trouble with the keyboard functionality. In the code below, only every second keypress is detected. Why is this please?

I'm on Windows 10 with Python 3.8.

from blessed import Terminal


term = Terminal()
print(f"{term.home}{term.black_on_skyblue}{term.clear}")

    
with term.cbreak(), term.hidden_cursor():
    while term.inkey() != 'q':
        inp = term.inkey()
        if inp.name == "KEY_LEFT":
            print("You pressed left")

Robin Andrews
  • 3,514
  • 11
  • 43
  • 111
  • Hey man, could you please provide some feedback on my answer? Did it solve your problem? – nordmanden Aug 24 '20 at 08:55
  • Well, it lead me to the solution, but the actual problem was the repeated call to `term.inkey()`, which should only happen once. Setting `inp` initially to `""` didn't work, as `None` has no attribute `name`. So I restructured using a `while True` loop. So thanks, but your answer isn't quite right as the first keypress is still ignored. – Robin Andrews Aug 24 '20 at 10:52
  • Glad you managed to solve it, but I do believe my answer is still correct. Your code does what you claim, only every second keypress is detected. However if you replace it with my code, every keypress is in fact detected, thus solving the initial problem. – nordmanden Aug 24 '20 at 10:55
  • Not quite so - the first keypress is missed, which is quite a significant problem. – Robin Andrews Aug 24 '20 at 14:06

1 Answers1

0

Move term.inkey() outside your inner while loop instead so it listens for keys first:

from blessed import Terminal
      
term = Terminal()
print(f"{term.home}{term.black_on_skyblue}{term.clear}")
    
        
with term.cbreak(), term.hidden_cursor():
    inp = term.inkey()
    while term.inkey() != 'q':
        if inp.name == "KEY_LEFT":
            print("You pressed left")
nordmanden
  • 340
  • 1
  • 10