Reputation: 75
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?
Upvotes: 0
Views: 577
Reputation:
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.
Upvotes: 0
Reputation: 7842
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:
and
http://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/
Upvotes: 2