简体   繁体   中英

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?

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/

You might want to use threads. This here is a very simple example:

#!/usr/bin/python

import time,readline,thread,sys

def counterThread():
    t = 0
        while True:
        t += 1
        if t % 50000000 == 0:
            print "now"

thread.start_new_thread(counterThread, ())
while True:
    s = raw_input('> ')
    print s

In this example the program counts up and every 50000000th loop it prints now. In the meantime you can input characters, which are right after that displayed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM