A brainfuck interpreter in Python.

So I implemented this small brainfuck interpreter in python. This implementation uses 8-bit memory cells and does not allow for for values outside the 0-255 range. If this happens a ValueError will be raised. By default, the memory tape is 5000 cells long, but this can be set by the user.

Python 2.6 or later is required.

Example:

bf = Brainfuck(100) #only 100 cells on the tape
twoPlusThree = "++>+++<[>+<-]"
bf.run_command(twoPlusThree)

And here is the implementation:

class Brainfuck:
	def __init__(self, tape_length=5000):
		self.tape = bytearray(tape_length)
		self.tape_pointer = 0
		
	def run_command(self, cmd):
		cmd_pointer = 0

		running = True
		while running:
			if self.tape_pointer > len(self.tape) or self.tape_pointer < 0 or cmd_pointer < 0 or cmd_pointer > len(cmd) -1:
				break

			if cmd[cmd_pointer] == "+":
				self.tape[self.tape_pointer] += 1
			elif cmd[cmd_pointer] == "-":
				self.tape[self.tape_pointer] -= 1
			elif cmd[cmd_pointer] == "<":
				self.tape_pointer -= 1
			elif cmd[cmd_pointer] == ">":
				self.tape_pointer += 1
			elif cmd[cmd_pointer] == ".":
				print(chr(self.tape[self.tape_pointer]))
			elif cmd[cmd_pointer] == ",":
				self.tape[self.tape_pointer] = int(raw_input())
			elif cmd[cmd_pointer] == "[":
				if int(self.tape[self.tape_pointer]) == 0:
					lbcounter = 0
					searching = True			
					while searching:
						cmdpointer +=1
						if cmd[cmd_pointer] == "[":
							lbcounter += 1
						elif lbcounter == 0 and cmd[cmd_pointer] == "]":
							searching = False 
						elif cmd[cmd_pointer] == "]":
							lbcounter -= 1
			elif cmd[cmd_pointer] == "]":
				if int(self.tape[self.tape_pointer]) != 0:
					rbcounter = 0
					searching = True			
					while searching:
						cmd_pointer -=1
						if cmd[cmd_pointer] == "]":
							rbcounter += 1
						elif rbcounter == 0 and cmd[cmd_pointer] == "[":
							searching = False
						elif cmd[cmd_pointer] == "[":
							rbcounter -= 1
			
			cmd_pointer += 1