[英]How to stop an infinite loop on the outside?
Consider the situation: i have the class(third-party library) with method that used infinity loop: 考虑一下情况:我有类(第三方库)和使用无限循环的方法:
class Worker(object):
...
def transator(self):
...
#if connected print data
while self.connected:
...
print data
if __name__ == "__main__":
worker = Worker()
worker.translator()
I use this class in my program and can not be changed. 我在我的程序中使用此类,无法更改。 ( I looked code on github :) ).
(我在github看了代码:))。 What the best method to stop this method manually ?
什么是手动停止此方法的最佳方法? I need change self.connected to False outside this method.
我需要在此方法之外更改self.connected到False。 I have an idea, but I think it's very complicated.
我有一个想法,但我认为这很复杂。
import time
from threading import Thread
class Terminator(Worker):
...
def terminate(self):
time.sleep(10)
self.connected = False
if __name__ == "__main__":
ter = Terminator()
t = Tread(target=ter.terminate)
t.start()
ter.translator()
Are there other ways? 还有其他方法吗?
Q: "How to stop an infinite loop on the outside"
问:“如何阻止外面的无限循环”
A: Read the documentation for the method/class which is using the infinite loop and look to see if there are any parameters which influence how it runs.
答:阅读使用无限循环的方法/类的文档,并查看是否有任何影响其运行方式的参数。
For your use case, it looks to me like you should just be able to pass the timeout parameter to the TwythonStreamer
constructor... 对于您的用例,它看起来像您应该只能将timeout参数传递给
TwythonStreamer
构造函数...
Alternatively to mcgilson correct answer you could add a property-descriptor like: 除了mcgilson正确的答案,你可以添加一个属性描述符,如:
def toggle_connect(self, singleton=[True]):
singleton[0] = not singleton[0]
return singleton
and after:
worker=Worker()
Worker.connected = property(toggle_connect)
You should be able to do something like the following: 您应该可以执行以下操作:
import time
from threading import Thread
if __name__ == "__main__":
w = Worker()
t = Thread(target=w.transator)
t.start()
time.sleep(10)
w.connected = False
t.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.