import socket def raw_sics_client(hostport): if ':' in hostport: host, port = hostport.split(':') hostport = (host, int(port)) sock = socket.create_connection(hostport, timeout=3) bbuf = b'' while True: try: reply = sock.recv(8192) # print(reply.decode('latin-1'), end='') if not reply: sock.close() return except socket.timeout: sock.close() return bbuf += reply blist = bbuf.split(b'\n') bbuf = blist.pop() for bline in blist: request = yield bline.decode('latin-1') if request is not None: sock.sendall(request.encode('latin-1') + b'\n') def check(sics, command, expected): reply = sics.send(command) if reply != expected: raise ValueError('expected %r but got %r' % (expected, reply)) def sics_coroutine(hostport, login): sics = raw_sics_client(hostport) check(sics, None, 'OK') check(sics, login, 'Login OK') request = yield while True: reply = sics.send('fulltransact %s' % request) while not reply.startswith('TRANSACTIONSTART'): reply = next(sics) reply = next(sics) result = [] while not reply.startswith('TRANSACTIONFINISHED'): result.append(reply) reply = next(sics) request = yield '\n'.join(result) def sics_client(hostport, command=None, login='Spy 007'): sics = sics_coroutine(hostport, login) next(sics) # start generator if command is None: return sics result = sics.send(command) sics.close() return result