<s> from twisted . internet import _threadedselect <EOL> _threadedselect . install ( ) <EOL> from twisted . internet . defer import Deferred <EOL> from twisted . python . failure import Failure <EOL> from twisted . internet import reactor <EOL> from twisted . python . runtime import seconds <EOL> from itertools import count <EOL> from Queue import Queue , Empty <EOL> class TwistedManager ( object ) : <EOL> def __init__ ( self ) : <EOL> self . twistedQueue = Queue ( ) <EOL> self . key = count ( ) <EOL> self . results = { } <EOL> def getKey ( self ) : <EOL> return self . key . next ( ) <EOL> def start ( self ) : <EOL> reactor . interleave ( self . twistedQueue . put ) <EOL> def _stopIterating ( self , value , key ) : <EOL> self . results [ key ] = value <EOL> def stop ( self ) : <EOL> key = self . getKey ( ) <EOL> reactor . addSystemEventTrigger ( '<STR_LIT>' , '<STR_LIT>' , <EOL> self . _stopIterating , True , key ) <EOL> reactor . stop ( ) <EOL> self . iterate ( key ) <EOL> def getDeferred ( self , d ) : <EOL> key = self . getKey ( ) <EOL> d . addBoth ( self . _stopIterating , key ) <EOL> res = self . iterate ( key ) <EOL> if isinstance ( res , Failure ) : <EOL> res . raiseException ( ) <EOL> return res <EOL> def poll ( self , noLongerThan = <NUM_LIT:1.0> ) : <EOL> base = seconds ( ) <EOL> try : <EOL> while ( seconds ( ) - base ) <= noLongerThan : <EOL> callback = self . twistedQueue . get_nowait ( ) <EOL> callback ( ) <EOL> except Empty : <EOL> pass <EOL> def iterate ( self , key = None ) : <EOL> while key not in self . results : <EOL> callback = self . twistedQueue . get ( ) <EOL> callback ( ) <EOL> return self . results . pop ( key ) <EOL> def fakeDeferred ( msg ) : <EOL> d = Deferred ( ) <EOL> def cb ( ) : <EOL> print "<STR_LIT>" <EOL> d . callback ( msg ) <EOL> reactor . callLater ( <NUM_LIT:2> , cb ) <EOL> return d <EOL> def fakeCallback ( ) : <EOL> print "<STR_LIT>" <EOL> def main ( ) : <EOL> m = TwistedManager ( ) <EOL> print "<STR_LIT>" <EOL> m . start ( ) <EOL> print "<STR_LIT>" <EOL> reactor . callLater ( <NUM_LIT:1> , fakeCallback ) <EOL> print "<STR_LIT>" <EOL> res = m . getDeferred ( fakeDeferred ( "<STR_LIT>" ) ) <EOL> print "<STR_LIT>" , res <EOL> print "<STR_LIT>" <EOL> m . stop ( ) <EOL> print "<STR_LIT>" <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> main ( ) </s>
