<s> import redis <EOL> from time import sleep <EOL> def message_handler ( data , message ) : <EOL> data . append ( ( message [ '<STR_LIT>' ] , message [ '<STR_LIT:data>' ] ) ) <EOL> class QuerySubscriber : <EOL> def __init__ ( self , host , port , msg_handler ) : <EOL> '''<STR_LIT>''' <EOL> pool = redis . ConnectionPool ( host = '<STR_LIT:localhost>' , port = <NUM_LIT> ) <EOL> r = redis . Redis ( connection_pool = pool ) <EOL> self . connection = r . pubsub ( ignore_subscribe_messages = True ) <EOL> self . queries = [ ] <EOL> self . _thread = None <EOL> self . handler = msg_handler <EOL> def add_query ( self , query ) : <EOL> self . queries . append ( query ) <EOL> self . _update ( ) <EOL> def start ( self ) : <EOL> queries = dict ( ( k , v ) for ( k , v ) in [ ( k , self . handler ) for k in self . queries ] ) <EOL> if len ( queries ) > <NUM_LIT:0> : <EOL> self . connection . subscribe ( ** queries ) <EOL> self . _thread = self . connection . run_in_thread ( sleep_time = <NUM_LIT> ) <EOL> else : <EOL> self . _thread = None <EOL> def _update ( self ) : <EOL> if self . _thread is not None : <EOL> self . _thread . stop ( ) <EOL> self . _thread = None <EOL> self . start ( ) <EOL> def close ( self ) : <EOL> try : <EOL> self . _thread . stop ( ) <EOL> except : <EOL> pass <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> mydata = [ ] <EOL> subscriber = QuerySubscriber ( "<STR_LIT:localhost>" , <NUM_LIT> , lambda x : message_handler ( mydata , x ) ) <EOL> query = None <EOL> while True : <EOL> if query is None : <EOL> query = raw_input ( "<STR_LIT>" ) <EOL> else : <EOL> subscriber . add_query ( query ) <EOL> query = None <EOL> print mydata </s>
