我有一个 cmd.Cmd 类命令行解释器,例如,它初始化 self.counter = Counter()。
调用“start”后,do_start()将调用self.counter.start(),self.counter启动一个从0计数到无穷大的while循环。
计数器的伪代码示例:
class Counter(object):
def __init__(self):
self.number = 0
self.running = False
def start():
self.running = True
while self.running:
self.number += 1
def status():
return self.number
def stop():
self.running = False
如何在 cmd.Cmd 类(调用 do_status())中调用“status”来获取 self.counter.status(),它将给出当前已增加的数字?
如何在 cmd.Cmd 类中调用“stop”来让 self.counter.stop() 停止 while 循环。
最佳答案
如果您想并行执行某些操作,则必须使用线程或多进程,如下所示:
import threading
from time import sleep
class Counter(object):
def __init__(self):
self.number = 0
self.running = False
def start(self):
self.running = True
while self.running:
self.number += 1
# add sleep to prevent blocking main thread by this loop
sleep(0.1)
def status(self):
return self.number
def stop(self):
self.running = False
class Cmd(object):
t = None
counter = None
def start(self):
self.counter = Counter()
self.t = threading.Thread(target=self.counter.start)
self.t.start()
def do_status(self):
return self.counter.status()
def stop(self):
self.counter.stop()
# waiting while thread with Counter will finish
self.t.join()
if __name__ == "__main__":
cmd = Cmd()
print "Starting counter"
cmd.start()
sleep(5)
print cmd.do_status()
sleep(2)
print cmd.do_status()
cmd.stop()
print "Counter was stopped"
输出将是:
Starting counter
50
70
Counter was stopped
但是如果您希望能够与来自不同应用程序的 Counter 进行通信,那么您必须了解 sockets .
关于python - 从外部停止正在运行的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27717384/