# Adapted from choukkkettte's code:
# http://forum.hardware.fr/hfr/Programmation/Python/automatisation-application-externe-sujet_125890_1.htm

from subprocess import *

class GDB:

	def __init__(self, pathToGdb):
		self.GDB_PROMPT = '(gdb) '
		self.GDB_CMDLINE = pathToGdb
		self.gdbProcess = Popen(self.GDB_CMDLINE , 0, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
		self.read_until_prompt()

	def read_until_prompt(self):
		buf = ''
		while(True):
			ch = self.gdbProcess.stdout.read(1)
			if not ch:
				return buf
			buf += ch
			if len(buf) < len(self.GDB_PROMPT):
				continue
			if buf.endswith(self.GDB_PROMPT):
				outlen = len(buf) - len(self.GDB_PROMPT)
				return buf[:outlen]
		
	def send(self, cmd):
		self.gdbProcess.stdin.write(cmd + '\n')
		output = self.read_until_prompt()
		return output
		
	def quit(self):
		self.send('quit')
