python - 从外部停止正在运行的 while 循环

标签 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())中调用“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/

相关文章:

python - 在 Python3 的 Tornado 上使用非阻塞 MySQL api 有什么建议吗?

java - 程序在 Eclipse 中运行但不在命令中运行?(不是类未定义或未找到)

c# - 使用 C# 控制 cmd.exe(发送和读取输出)

python - 在字典声明中使用 OrderedDict

python - newB 在 Udacity Computer 与 Backus Naur 斗争。科学。 101

python - 如何手动创建 scikit-learn 树?

linux - 使用重命名工具删除大写字母之前的字符

linux - 在终端中访问带有重音符号/Unicode 的文件名

windows - 命令行 : "-" converted to "û"

windows - 用于替换多个文件中特定字符串的批处理脚本