<s> import optparse , sys <EOL> from twisted . internet . protocol import Protocol , ClientFactory <EOL> def parse_args ( ) : <EOL> usage = """<STR_LIT>""" <EOL> parser = optparse . OptionParser ( usage ) <EOL> _ , addresses = parser . parse_args ( ) <EOL> if not addresses : <EOL> print parser . format_help ( ) <EOL> parser . exit ( ) <EOL> def parse_address ( addr ) : <EOL> if '<STR_LIT::>' not in addr : <EOL> host = '<STR_LIT:127.0.0.1>' <EOL> port = addr <EOL> else : <EOL> host , port = addr . split ( '<STR_LIT::>' , <NUM_LIT:1> ) <EOL> if not port . isdigit ( ) : <EOL> parser . error ( '<STR_LIT>' ) <EOL> return host , int ( port ) <EOL> return map ( parse_address , addresses ) <EOL> class PoetryProtocol ( Protocol ) : <EOL> poem = '<STR_LIT>' <EOL> def dataReceived ( self , data ) : <EOL> self . poem += data <EOL> def connectionLost ( self , reason ) : <EOL> self . poemReceived ( self . poem ) <EOL> def poemReceived ( self , poem ) : <EOL> self . factory . poem_finished ( poem ) <EOL> class PoetryClientFactory ( ClientFactory ) : <EOL> protocol = PoetryProtocol <EOL> def __init__ ( self , callback , errback ) : <EOL> self . callback = callback <EOL> self . errback = errback <EOL> def poem_finished ( self , poem ) : <EOL> self . callback ( poem ) <EOL> def clientConnectionFailed ( self , connector , reason ) : <EOL> self . errback ( reason ) <EOL> def get_poetry ( host , port , callback , errback ) : <EOL> """<STR_LIT>""" <EOL> from twisted . internet import reactor <EOL> factory = PoetryClientFactory ( callback , errback ) <EOL> reactor . connectTCP ( host , port , factory ) <EOL> def poetry_main ( ) : <EOL> addresses = parse_args ( ) <EOL> from twisted . internet import reactor <EOL> poems = [ ] <EOL> errors = [ ] <EOL> def got_poem ( poem ) : <EOL> poems . append ( poem ) <EOL> poem_done ( ) <EOL> def poem_failed ( err ) : <EOL> print >> sys . stderr , '<STR_LIT>' , err <EOL> errors . append ( err ) <EOL> poem_done ( ) <EOL> def poem_done ( ) : <EOL> if len ( poems ) + len ( errors ) == len ( addresses ) : <EOL> reactor . stop ( ) <EOL> for address in addresses : <EOL> host , port = address <EOL> get_poetry ( host , port , got_poem , poem_failed ) <EOL> reactor . run ( ) <EOL> for poem in poems : <EOL> print poem <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> poetry_main ( ) </s>
