Guest User

Untitled

a guest
Apr 26th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. import inspect
  2.  
  3. class Commands(list):
  4. def __init__(self, commands):
  5. commands = commands if commands else []
  6.  
  7. if not hasattr(commands, '__iter__'):
  8. commands = [commands]
  9.  
  10. super(Commands, self).__init__(commands)
  11.  
  12. def match(self, expression):
  13. for command in self:
  14. if command.matches(expression):
  15. return command
  16.  
  17. class Interpreter:
  18.  
  19. def __init__(self, commands=None):
  20. self.commands = Commands(commands)
  21. self.vars = {}
  22.  
  23. def interpret(self, expression):
  24. try:
  25. return eval(expression, {}, self.vars)
  26. except NameError:
  27. matching_command = self.commands.match(expression)
  28.  
  29. if matching_command:
  30. execute_method = matching_command.execute
  31. parameter_name = inspect.getargspec(execute_method)[0][0]
  32.  
  33. if parameter_name == 'variables':
  34. return matching_command.execute(self.vars)
  35. else:
  36. return matching_command.execute(self.commands)
  37. else:
  38. return 'null'
  39. except SyntaxError:
  40. l_value, r_value = expression.split('=')
  41.  
  42. try:
  43. self.vars[l_value] = int(r_value)
  44. except ValueError:
  45. self.vars[l_value] = self.interpret(r_value)
Add Comment
Please, Sign In to add comment