How to break a while true with keyboard interruption?

心不动则不痛 提交于 2019-12-24 06:50:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!