Python - Infinite while loop, break on user input

前端 未结 6 1296
挽巷
挽巷 2020-12-01 22:14

I have an infinite while loop that I want to break out of when the user presses a key. Usually I use raw_input to get the user\'s response; however, I need

6条回答
  •  情歌与酒
    2020-12-01 22:20

    Using the msvcrt module as thebjorn recommended I was able to come up with something that works. The following is a basic example that will exit the loop if any key is pressed, not just enter.

    import msvcrt, time
    i = 0
    while True:
        i = i + 1
        if msvcrt.kbhit():
            break
        time.sleep(0.1)
    print i
    

提交回复
热议问题