使用类级变量循环时停止

2024-10-04 11:26:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个监控系统,一旦启动应用程序,它将持续监控更改并将结果输出到数据库。为此,我使用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条件。 (我不得不中断命令行来停止应用程序)

确切地说,当循环运行时,如何将类级标志设置为false

注意:这个标志的变化发生在外部输入中,比如用户想要停止系统,但在循环内部条件满足时不会发生


Tags: 代码命令行selftrue应用程序标志系统def
2条回答

使用下面的代码,您可以暂时停止监视,也可以完全退出监视

import threading
import time

class Monitor(threading.Thread):
    def __init__(self):
        self.b_quit = False
        self.monitor = True
        self.event = threading.Event()  # Whenever this event is set, monitoring should happen
        self.event.set()  # By default turn on monitoring
        threading.Thread.__init__(self)

    def run(self):
        i = 0
        while self.monitor:
            eventSet = self.event.wait()
            if not self.monitor or self.b_quit:
                break

            print("   Thread is active: {}".format(i), end='\r')
            i += 1

    def begin(self):
        self.event.set()

    def halt(self):
        self.event.clear()

    def quit(self):
        self.event.set()
        self.b_quit = True


obj = Monitor()
obj.start() # Launches a separate thread which can be controlled, based upon calls to begin, halt, and quit
time.sleep(1)
print("Trigger halt from main thread")
obj.halt()  # Only paused the monitoring
time.sleep(1)
print("Trigger resume from main thread")
obj.begin()  # Resumes the monitoring
time.sleep(1)
print("Trigger quit from main thread")
obj.quit()   # Exits the thread completely

在不同的线程中启动循环,这样就不会失去对程序的控制

import threading
class Monitor:

    (....)

    def start(self):
        threading.Thread(target=self.run).start()

    def run(self):
        i=0
        while self.monitor:
             i += 1

相关问题 更多 >