Python: How to get input from console while an infinite loop is running?

Another way to do it involves threads.

import threading

# define a thread which takes input
class InputThread(threading.Thread):
    def __init__(self):
        super(InputThread, self).__init__()
        self.daemon = True
        self.last_user_input = None

    def run(self):
        while True:
            self.last_user_input = input('input something: ')
            # do something based on the user input here
            # alternatively, let main do something with
            # self.last_user_input

# main
it = InputThread()
it.start()
while True:
    # do something  
    # do something with it.last_user_input if you feel like it

Leave a Comment