Python - Infinite while loop, break on user input

前端 未结 6 1289
挽巷
挽巷 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

    I could not get some of the popular answers working. So I came up with another approach using the CTRL + C to plug in user input and imbibe a keyboard interrupt. A simple solution can be using a try-catch block,

    i = 0
    try:
        while True:
            i+=1
            print(i)
            sleep(1)
    except:
        pass
    # do what you want to do after it...
    

    I got this idea from running a number of servers like flask and django. This might be slightly different from what the OP asked, but it might help someone else who wanted a similar thing.

提交回复
热议问题