How to use threading to get user input realtime while main still running in python

You really need to be more specific. Why do these need to be in threads? You should show us what you have tried, or describe in more detail what you are trying to accomplish.

In your current setup, you are putting the thread inside a loop, so it can’t run independently of each user input.

edited: here is some cleaned up code as an example for you, based on your post edits and comments.

import threading
import time
import sys

def background():
    while True:
        time.sleep(3)
        print 'disarm me by typing disarm'


def other_function():
    print 'You disarmed me! Dying now.'

# now threading1 runs regardless of user input
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()

while True:
    if raw_input() == 'disarm':
        other_function()
        sys.exit()
    else:
        print 'not disarmed'

Leave a Comment