异步 的 twisted  , 按照同步的思路去写代码  例子

  1. from twisted.internet.defer import inlineCallbacks, Deferred 
  2.  
  3. #演示内部休息多少秒 
  4. def inline_sleep(t): 
  5.     print 'sleep',t 
  6.  
  7.     d = Deferred() 
  8.     reactor.callLater(t,d.callback,1
  9.     return d 
  10.  
  11. def test_fun_run(): 
  12.     sys.stdout.write('.'); 
  13.     sys.stdout.flush(); 
  14.     reactor.callLater(0.2,test_fun_run) 
  15.          
  16.      
  17. def f(html): 
  18.     return html  
  19. @inlineCallbacks 
  20. def test3(): 
  21.      
  22.     reactor.callLater(1,test_fun_run) 
  23.     p=getPage('http://localhost/'
  24.     p.addCallback(f) 
  25.     a=yield p 
  26.     print 'a1:html len',len(a) 
  27.     #import time;time.sleep(t)  使用此函数twisted 停止运行了 
  28.     yield inline_sleep(12
  29.      
  30.     p=getPage('http://localhost/2.html'
  31.     p.addCallback(f) 
  32.     try
  33.         a=yield p 
  34.         print 'a2',len(a) 
  35.     except:pass 
  36.  
  37.     reactor.stop() 
  38.      
  39. def run_start3(): 
  40.     print 'run' 
  41.     reactor.callLater(1,test3) 
  42.     reactor.run()