0

I want to break out of a loop by a keystroke. But not at any time. I want the current iteration of the loop to finish up and then exit the loop.

All similar question I found mostly suggest catching KeyboardInterrupt, so I hope this is no duplicate.

petezurich
  • 9,280
  • 9
  • 43
  • 57
Menacer
  • 23
  • 1
  • 5
  • Just check for keyboard interrupt at the end of the loop. If you got one, break out of it – Andrew Scott Apr 14 '19 at 13:43
  • @AndrewScott But KeyboardInterrupt is an asynchronous exception. You cannot "check for it", it arrives uninvited and interrupts whatever code is currently running, immediately. – ivan_pozdeev Apr 14 '19 at 13:55

1 Answers1

0

At the end of an iteration, check if there was a keypress by any of the methods listed in Polling the keyboard (detect a keypress) in python and break out of the loop if there was.

E.g. with the cross-platform implementation of kbhit:

while True:
    do_something()
    if kbhit(): break
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • thanks, I guess. The select module seems very complicated, though. You seem to be able to do a lot of advanced stuff with it. It really gives me a headache to understand all of it. Could you provide a code example for my usecase using the select module? – Menacer Apr 15 '19 at 07:57