外部停止运行while循环

时间:2014-12-31 06:53:44

标签: python command-line cmd command command-line-arguments

我有一个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())中获取self.counter.status(),它将给出已递增的当前数字?

我该怎么称呼'停止'在我的cmd.Cmd类中,让self.counter.stop()停止while循环。

2 个答案:

答案 0 :(得分:3)

如果你想并行做某事,你必须使用线程或多个这样的过程:

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

答案 1 :(得分:0)

如果cmdCmd的实例并且您使用实例方法

将实例发送到Counter

def __init__(self, cmd):
    self.number = 0
    # self.running = False # removed - use self.cmd.status() for control
    self.cmd = cmd

使用while控制self.cmd

def start():
    while self.cmd.status():
        self.number += 1

我希望self.cmd.status()能够阻止(期待用户输入,或类似的东西)。