Search code examples
pythonmultithreadingraw-input

How to do other stuff while user deciding if write anything in raw_input?


while True:
  mess = raw_input('Type: ')
  //other stuff

While user doesn't type anything, I can't do //other stuff. How can I do, that other stuff would be executed, but, if user types anything at that time, mess would change its value?


Solution

  • You should spawn your other stuff in a worker thread.

    import threading
    import time
    import sys
    
    mess = 'foo'
    
    def other_stuff():
      while True:
        sys.stdout.write('mess == {}\n'.format(mess))
        time.sleep(1)
    
    t = threading.Thread(target=other_stuff)
    t.daemon=True
    t.start()
    
    while True:
      mess = raw_input('Type: ')
    

    This is a trivial example with mess as a global. Note that for thread-safe passing of objects between worker thread and main thread, you should use a Queue object to pass things between threads, don't use a global.