prompt.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """Routines that install Adventure commands for the Python prompt.
  2. Copyright 2010-2015 Brandon Rhodes. Licensed as free software under the
  3. Apache License, Version 2.0 as detailed in the accompanying README.txt.
  4. """
  5. import inspect
  6. class ReprTriggeredPhrase(object):
  7. """Command that happens when Python calls repr() to print them."""
  8. def __init__(self, game, words):
  9. self.game = game
  10. self.words = tuple(words) # protect against caller changing list
  11. def __repr__(self):
  12. """Run this command and return the message that results."""
  13. output = self.game.do_command(self.words)
  14. return output.rstrip('\n') + '\n'
  15. def __call__(self, arg=None):
  16. """Return a compound command of several words, like `get(keys)`."""
  17. if arg is None:
  18. return self
  19. words = arg.words if isinstance(arg, ReprTriggeredPhrase) else (arg,)
  20. return ReprTriggeredPhrase(self.game, self.words + words)
  21. def __getattr__(self, name):
  22. return ReprTriggeredPhrase(self.game, self.words + (name,))
  23. def install_words(game):
  24. # stack()[0] is this; stack()[1] is adventure.play(); so, stack()[2]
  25. namespace = inspect.stack()[2][0].f_globals
  26. words = [ k for k in game.vocabulary if isinstance(k, str) ]
  27. words.append('yes')
  28. words.append('no')
  29. for word in words:
  30. identifier = ReprTriggeredPhrase(game, [ word ])
  31. namespace[word] = identifier
  32. if len(word) > 5:
  33. namespace[word[:5]] = identifier