Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the WHILE loop, I wanna run two function, one is base function, which will run everytime, the other is user_input function, when user input 'disarm', program can run user_input function. This two function need in WHILE loop so can run all the time.

How could I do to write a function to accomplish this?

Because its realtime so I cant add time.sleep in threading.

Thanks.

import threading

class BackInput(threading.Thread):
    def __init__(self):
        super(BackInput, self).__init__()


    def run(self):
        self.input = raw_input()

while True:
    threading1 = BackInput()
    threading1.start()
    threading1.join()
    if threading1.input == 'disarm':
        print 'Disarm'
        break
    print 'Arm'

In this code, the program should print Arm every second, when I typed disarm, it can print Disarm and break it.

like image 861
VValkyrja Avatar asked Aug 02 '15 05:08

VValkyrja


1 Answers

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'
like image 146
Michael Neylon Avatar answered Oct 13 '22 17:10

Michael Neylon