问题
How can I break a while True if I press a key?, and if it is possible, how can I break a while True if a press an x key (e.g. intro
)?.
while True:
if something is pressed:
print("STOP")
break
do_something()
I tryied with inputs but you can't put:
while True:
i = input() or None if program wait > 3 seconds. # > = more than
if != None:
print("STOP")
break
do_something()
Input stop all the while waiting for answer, and i don't want that.
PD: I use win 10 64-bits, python 32-bits 3.6, terminal.
PD2: Before post this question I search more about it, i found:
while True:
try:
do_something()
except KeyboardInterrupt:
pass
But this only stop with Ctrl + c
, not other keys.
回答1:
This only works in Windows:
import msvcrt
while True:
if msvcrt.kbhit():
break
The msvcrt provide a list of functions capables of process key inputs. msvcrt.kbhit()
check if a key was pressed and it's waiting for been read and return true or false based on that.
来源:https://stackoverflow.com/questions/43533135/how-to-break-a-while-true-with-keyboard-interruption