<s> import sys <EOL> from threading import Thread <EOL> try : <EOL> from Queue import Queue , Empty <EOL> except ImportError : <EOL> from queue import Queue , Empty <EOL> ON_POSIX = '<STR_LIT>' in sys . builtin_module_names <EOL> class CliSession ( ) : <EOL> def __init__ ( self , process ) : <EOL> self . process = process <EOL> self . stdout = Queue ( ) <EOL> self . stderr = Queue ( ) <EOL> self . thread_out = Thread ( target = self . __enqueue_output , args = ( process . stdout , self . stdout ) ) <EOL> self . thread_err = Thread ( target = self . __enqueue_output , args = ( process . stderr , self . stderr ) ) <EOL> for t in [ self . thread_out , self . thread_err ] : <EOL> t . daemon = True <EOL> t . start ( ) <EOL> self . __outputs = [ ] <EOL> self . __errors = [ ] <EOL> def do ( self , query ) : <EOL> self . __read_all ( ) <EOL> self . process . stdin . write ( query + '<STR_LIT>' ) <EOL> return self <EOL> def last_output ( self ) : <EOL> self . __read_output ( ) <EOL> return self . __outputs [ - <NUM_LIT:1> ] <EOL> def last_error ( self ) : <EOL> self . __read_errors ( ) <EOL> return self . __errors [ - <NUM_LIT:1> ] <EOL> def outputs ( self ) : <EOL> self . __read_output ( ) <EOL> return self . __outputs <EOL> def errors ( self ) : <EOL> self . __read_errors ( ) <EOL> return self . __errors <EOL> def has_errors ( self ) : <EOL> self . __read_errors ( ) <EOL> for err in self . __errors : <EOL> if '<STR_LIT>' not in err and err != '<STR_LIT>' : <EOL> return True <EOL> return False <EOL> def close ( self ) : <EOL> self . process . stdin . write ( '<STR_LIT>' ) <EOL> self . process . wait ( ) <EOL> def __read_all ( self ) : <EOL> self . __read_output ( ) <EOL> self . __read_errors ( ) <EOL> def __read_output ( self ) : <EOL> r = self . __read ( self . stdout ) <EOL> if r : <EOL> self . __outputs . append ( r ) <EOL> def __read_errors ( self ) : <EOL> r = self . __read ( self . stderr ) <EOL> if r : <EOL> self . __errors . append ( r ) <EOL> def __read ( self , queue ) : <EOL> output = None <EOL> while True : <EOL> try : <EOL> line = queue . get ( timeout = <NUM_LIT> ) <EOL> except Empty : <EOL> return output <EOL> else : <EOL> output = line if output is None else output + line <EOL> def __enqueue_output ( self , out , queue ) : <EOL> for line in iter ( out . readline , '<STR_LIT>' ) : <EOL> queue . put ( line ) <EOL> out . close ( ) </s>
