考虑使用threading.Thread
:
import time
import threading
class MyTimer(threading.Thread):
def __init__(self):
self.h = 0
self.m = 0
self.s = 0
def count(self, t, stop_event):
while self.s <= 60:
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
time.sleep(1)
self.s += 1
if self.s == 60:
self.m += 1
self.s = 0
elif self.m == 60:
self.h += 1
self.m = 0
self.s = 0
elif stop_event.is_set():
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
break
class Asking(threading.Thread):
def asking(self, t, stop_event):
while not stop_event.is_set():
word = raw_input('enter a word:\n')
if word == 'bye':
timer_stop.set()
question_stop.set()
timer = MyTimer()
question = Asking()
question_stop = threading.Event()
timer_stop = threading.Event()
threading.Thread(target=question.asking, args=(1, question_stop)).start()
threading.Thread(target=timer.count, args=(2, timer_stop)).start()
以运行它为例:
$ python stackoverflow.py
enter a word:
0 Hours 0 Minutes 0 Seconds
0 Hours 0 Minutes 1 Seconds
0 Hours 0 Minutes 2 Seconds
0 Hours 0 Minutes 3 Seconds
hi
enter a word:
0 Hours 0 Minutes 4 Seconds
0 Hours 0 Minutes 5 Seconds
0 Hours 0 Minutes 6 Seconds
bye
0 Hours 0 Minutes 7 Seconds
代码可能会更整洁:p。我震惊自己,我能够制作这个:D。