Search code examples
pythonbackgroundraw-input

How do I make my code do things in the background


While I'm waiting for an input how can I make sure my code is doing other things? for example..

Say I want to count to 10 while I get input That would be useless of course, but I have reasons for learning this...

    test = 0
    while test < 11:
       test += 1
       print test
       raw_input("taking input")

Obviously it's gonna stop for input each time. How can I make it count as the user is giving input?


Solution

  • If you just need something that can count while the user enters input, you can use a thread:

    from threading import Thread,Event
    from time import sleep
    
    class Counter(Thread):
        def __init__(self):
            Thread.__init__(self)
            self.count = 0
            self._stop = Event()
    
        def run(self):
            while not self._stop.is_set():
                sleep(1)
                self.count+=1 
    
        def stop(self):
            self._stop.set()
    
    
    count = Counter()
    
    # here we create a thread that counts from 0 to infinity(ish)
    count.start()
    
    # raw_input is blocking, so this will halt the main thread until the user presses enter
    raw_input("taking input")
    
    # stop and read the counter
    count.stop()
    print "User took %d seconds to enter input"%count.count
    

    If you want to stop the raw_input after n seconds if no input has been entered by the user, then this is slightly more complicated. The most straight forward way to do this is probably using select (although not if you are on a Windows machine). For examples, see:

    raw_input and timeout

    and

    http://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/