Execute Brain****/Python

From Rosetta Code
Revision as of 15:42, 6 December 2009 by 216.99.99.42 (talk) (no need for temp)
Execute Brain****/Python is an implementation of Brainf***. Other implementations of Brainf***.
Execute Brain****/Python is part of RCBF. You may find other members of RCBF at Category:RCBF.

Quick implementation of a Brainfuck interpreter in Python.

<lang python>

  1. !/usr/bin/python

from __future__ import with_statement

import sys

class BrainFuck():

   def __init__(self):
       self.instructions = 
   
   def main(self):
       if len(sys.argv[1:]) > 0:
           source_file = sys.argv[1]
           with open(source_file) as source_handle:
               self.instructions = source_handle.read()
       else:
           print >> sys.stderr, 'No source file.'
           sys.exit(2)
       
       self.match_braces()
   
   def match_braces(self):
       loops = {}
       loop_stack = []
       
       for ptr, instruction in enumerate(self.instructions):
           if instruction == '[':loop_stack.append(ptr)
           elif instruction == ']':loops[ptr],loops[loops[ptr]] = loop_stack.pop(),ptr
       
       self.start_interpreting(loops)
   
   def start_interpreting(self, loops):
       tape = [0] * 30000
       cell = 0
       pointer = 0
       
       while pointer < len(self.instructions):
           instruction = self.instructions[pointer]
           
           if instruction == '>':
               cell += 1
           elif instruction == '<':
               cell -= 1
           elif instruction == '+':
               tape[cell] += 1
           elif instruction == '-':
               tape[cell] -= 1
           elif instruction == ',':
               tape[cell] = ord(sys.stdin.read(1))
           elif instruction == '.':
               sys.stdout.write(chr(tape[cell]))
           elif instruction == '[' and tape[cell] == 0:
               pointer = loops[pointer]
           elif instruction == ']' and tape[cell] != 0:
               pointer = loops[pointer]
           
           pointer += 1
           

if __name__ == "__main__":

   interpreter = BrainFuck()
   interpreter.main()

</lang>