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

input, loops, python

Solution

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

Problem

I'm trying to write a simple Python IRC client. So far I can read data, and I can send data back to the client if it automated. I'm getting the data in a `while True`, which means that I cannot enter text while at the same time reading data. How can I enter text in the console, that only gets sent when I press enter, while at the same time running an infinite loop? Basic code structure: ``` while True: read data #here is where I want to write data only if it contains '/r' in it ```

Original source

Related problems