pip install Twisted
安装Twisted库
from twisted.internet import reactor#开启事件循环#不是简单的循环#不会带来任何性能损失reactor.run()
1. Twisted的reactor只有通过调用reactor.run()才启动。
2. reactor循环是在其开始的线程中运行,也就是运行在主线程中。
3. 一旦启动,reactor就会在程序的控制下(或者具体在一个启动它的线程的控制下)一直运行下去。
4. reactor空转时并不会消耗任何CPU的资
5. 并不需要显式的创建reactor,只需要引入就OK。
from twisted.internet import pollreactor#将会使用poll而不是默认的selectpollreactor.install()
一般的写法:
from twited.internet import pollreactorpollreactor.install()from twisted.internet import reactoreactor.run()
一个简单的demo
#一个简单的demofrom twisted.internet import reactordef hello(): print('hello from the reactor loop!') print('hhh')reactor.callWhenRunning(hello)print('start the reactor')reactor.run()
回调的重要特性:
1. 我们的代码与Twisted代码运行在同一个线程中。
2. 当我们的代码运行时,Twisted代码是处于暂停状态的。
3. 同样,当Twisted代码处于运行状态时,我们的代码处于暂停状态。
4. reactor事件循环会在我们的回调函数返回后恢复运
特别需要强调的是,我们应该尽量避免在回调函数中使用会阻塞I/O的函数。
from twisted.internet import reactorclass Countdown(object): counter = 5 def count(self): if self.counter == 0: #reactor停止 reactor.stop() else: print(self.counter, '...') self.counter -= 1 #注册回调函数 reactor.callLater(1, self.count)#添加reactor将要执行的函数reactor.callWhenRunning(Countdown().count)#开始print('start')reactor.run()#结束print('stop')