Search code examples
pythonloopsinputblock

How to read users input when in loop (and without blocking work in this loop)?


How to read users input when in loop (and without blocking work in this loop)?

I want to do some basic stuff, like switching DEBUG variable, print values of some variables etc on some specific keys that user will print, but my program work in constant loop, and this loop fire another threads. How can i do this?


Solution

  • Use threads:

    import threading
    import time
    
    value = 3
    
    def process():
        while True:
            print(value)
            time.sleep(1)
    
    thread = threading.Thread(target=process)
    thread.start()
    
    while True:
        value = input('Enter value: ')
    

    (Output gets kind of messed up here because of both loops printing stuff to the terminal but I think the idea should be clear.)