异步 的 twisted , 按照同步的思路去写代码 例子
- from twisted.internet.defer import inlineCallbacks, Deferred
- #演示内部休息多少秒
- def inline_sleep(t):
- print 'sleep',t
- d = Deferred()
- reactor.callLater(t,d.callback,1)
- return d
- def test_fun_run():
- sys.stdout.write('.');
- sys.stdout.flush();
- reactor.callLater(0.2,test_fun_run)
- def f(html):
- return html
- @inlineCallbacks
- def test3():
- reactor.callLater(1,test_fun_run)
- p=getPage('http://localhost/')
- p.addCallback(f)
- a=yield p
- print 'a1:html len',len(a)
- #import time;time.sleep(t) 使用此函数twisted 停止运行了
- yield inline_sleep(12)
- p=getPage('http://localhost/2.html')
- p.addCallback(f)
- try:
- a=yield p
- print 'a2',len(a)
- except:pass
- reactor.stop()
- def run_start3():
- print 'run'
- reactor.callLater(1,test3)
- reactor.run()
转载于:https://blog.51cto.com/shendongming/617084