Exiting while loop by pressing enter without blocking. How can I improve this method?

前端 未结 1 1891
长情又很酷
长情又很酷 2020-12-04 00:00

So I\'ve been doing a little bit of reading up on how to exit a while loop by the user pressing the enter key and I\'ve come up with the following:

import sy         


        
相关标签:
1条回答
  • 2020-12-04 00:03

    This worked for me:

    import sys, select, os
    
    i = 0
    while True:
        os.system('cls' if os.name == 'nt' else 'clear')
        print "I'm doing stuff. Press Enter to stop me!"
        print i
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            line = raw_input()
            break
        i += 1
    

    You only need to check for the stdin being input once (since the first input will terminate the loop). If the conditions line/not line have result for you, you can combine them to one if statement. Then, with only one while statement being used, you can now use break instead of setting a flag.

    0 讨论(0)
提交回复
热议问题