Python - Infinite while loop, break on user input

前端 未结 6 1303
挽巷
挽巷 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:42

    You can use non-blocking read from stdin:

    import sys
    import os
    import fcntl
    import time
    
    fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
    fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
    while True:
        print("Waiting for user input")
        try:
            stdin = sys.stdin.read()
            if "\n" in stdin or "\r" in stdin:
                break
        except IOError:
            pass
        time.sleep(1)
    

提交回复
热议问题