Search code examples
pythonloopsraw-input

How to keep a While True loop running with raw_input() if inputs are seldom?


I'm currently working on a project where I need to send data via Serial persistently but need to occasionally change that data based in new inputs. My issue is that my current loop only functions exactly when a new input is offered by raw_input(). Nothing runs again until another raw_input() is received.

My current (very slimmed down) loop looks like this:

while True:
    foo = raw_input()
    print(foo)

I would like for the latest values to be printed (or passed to another function) constantly regardless of how often changes occur.

Any help is appreciated.


Solution

  • How will you type in your data at the same time while data is being printed?

    However, you can use multithreading if you make sure your source of data doesn't interfere with your output of data.

    import thread
    
    def give_output():
        while True:
            pass  # output stuff here
    
    def get_input():
        while True:
            pass  # get input here
    
    thread.start_new_thread(give_output, ())
    thread.start_new_thread(get_input, ())
    

    Your source of data could be another program. You could connect them using a file or a socket.