我正在构建一个监控系统,一旦启动应用程序,它将持续监控变化并将结果输出到数据库。为此,我使用 while 循环来连续监控重复任务。在这里,我使用类级变量作为 while 循环中的条件的“True”。在这里,我遇到了当应用程序在 while 循环中运行时如何将标志更改为“False”的问题。
示例代码如下:
class Monitor:
def __init__(self):
self.monitor=True
def start(self):
i=0
while(self.monitor):
i+=1
我正在运行以下几行来在命令行中运行代码:
>>> from StartStopMontoring import Monitor
>>> m=Monitor()
>>> m.start()
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/DATA/Innominds/WorkSpace/Python/StartStopMontoring.py", line 7, in start
while(self.monitor):
KeyboardInterrupt
>>>
第二行创建对象,第三行调用函数,然后我无法将标志设置为 false,因为它处于 while 循环中,并且始终满足 true 条件。 (我必须中断命令行才能停止应用程序)。
准确地说,当 while 循环运行时,如何将类级别标志设置为 false?
注意:此标志更改是由外部输入发生的,例如用户想要停止系统,但当循环内部满足条件时则不会发生更改。
最佳答案
在不同的线程中启动循环,这样您就不会失去对程序的控制。
import threading
class Monitor:
(....)
def start(self):
threading.Thread(target=self.run).start()
def run(self):
i=0
while self.monitor:
i += 1
关于python - 使用类级别变量停止 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58948742/