code.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """Utilities needed to emulate Python's interactive interpreter.
  2. """
  3. # Inspired by similar code by Jeff Epler and Fredrik Lundh.
  4. import sys
  5. import traceback
  6. from codeop import CommandCompiler, compile_command
  7. __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact",
  8. "compile_command"]
  9. def softspace(file, newvalue):
  10. oldvalue = 0
  11. try:
  12. oldvalue = file.softspace
  13. except AttributeError:
  14. pass
  15. try:
  16. file.softspace = newvalue
  17. except (AttributeError, TypeError):
  18. # "attribute-less object" or "read-only attributes"
  19. pass
  20. return oldvalue
  21. class InteractiveInterpreter:
  22. """Base class for InteractiveConsole.
  23. This class deals with parsing and interpreter state (the user's
  24. namespace); it doesn't deal with input buffering or prompting or
  25. input file naming (the filename is always passed in explicitly).
  26. """
  27. def __init__(self, locals=None):
  28. """Constructor.
  29. The optional 'locals' argument specifies the dictionary in
  30. which code will be executed; it defaults to a newly created
  31. dictionary with key "__name__" set to "__console__" and key
  32. "__doc__" set to None.
  33. """
  34. if locals is None:
  35. locals = {"__name__": "__console__", "__doc__": None}
  36. self.locals = locals
  37. self.compile = CommandCompiler()
  38. def runsource(self, source, filename="<input>", symbol="single"):
  39. """Compile and run some source in the interpreter.
  40. Arguments are as for compile_command().
  41. One several things can happen:
  42. 1) The input is incorrect; compile_command() raised an
  43. exception (SyntaxError or OverflowError). A syntax traceback
  44. will be printed by calling the showsyntaxerror() method.
  45. 2) The input is incomplete, and more input is required;
  46. compile_command() returned None. Nothing happens.
  47. 3) The input is complete; compile_command() returned a code
  48. object. The code is executed by calling self.runcode() (which
  49. also handles run-time exceptions, except for SystemExit).
  50. The return value is True in case 2, False in the other cases (unless
  51. an exception is raised). The return value can be used to
  52. decide whether to use sys.ps1 or sys.ps2 to prompt the next
  53. line.
  54. """
  55. try:
  56. code = self.compile(source, filename, symbol)
  57. except (OverflowError, SyntaxError, ValueError):
  58. # Case 1
  59. self.showsyntaxerror(filename)
  60. return False
  61. if code is None:
  62. # Case 2
  63. return True
  64. # Case 3
  65. self.runcode(code)
  66. return False
  67. def runcode(self, code):
  68. """Execute a code object.
  69. When an exception occurs, self.showtraceback() is called to
  70. display a traceback. All exceptions are caught except
  71. SystemExit, which is reraised.
  72. A note about KeyboardInterrupt: this exception may occur
  73. elsewhere in this code, and may not always be caught. The
  74. caller should be prepared to deal with it.
  75. """
  76. try:
  77. exec code in self.locals
  78. except SystemExit:
  79. raise
  80. except:
  81. self.showtraceback()
  82. else:
  83. if softspace(sys.stdout, 0):
  84. print
  85. def showsyntaxerror(self, filename=None):
  86. """Display the syntax error that just occurred.
  87. This doesn't display a stack trace because there isn't one.
  88. If a filename is given, it is stuffed in the exception instead
  89. of what was there before (because Python's parser always uses
  90. "<string>" when reading from a string).
  91. The output is written by self.write(), below.
  92. """
  93. type, value, sys.last_traceback = sys.exc_info()
  94. sys.last_type = type
  95. sys.last_value = value
  96. if filename and type is SyntaxError:
  97. # Work hard to stuff the correct filename in the exception
  98. try:
  99. msg, (dummy_filename, lineno, offset, line) = value
  100. except:
  101. # Not the format we expect; leave it alone
  102. pass
  103. else:
  104. # Stuff in the right filename
  105. value = SyntaxError(msg, (filename, lineno, offset, line))
  106. sys.last_value = value
  107. list = traceback.format_exception_only(type, value)
  108. map(self.write, list)
  109. def showtraceback(self):
  110. """Display the exception that just occurred.
  111. We remove the first stack item because it is our own code.
  112. The output is written by self.write(), below.
  113. """
  114. try:
  115. type, value, tb = sys.exc_info()
  116. sys.last_type = type
  117. sys.last_value = value
  118. sys.last_traceback = tb
  119. tblist = traceback.extract_tb(tb)
  120. del tblist[:1]
  121. list = traceback.format_list(tblist)
  122. if list:
  123. list.insert(0, "Traceback (most recent call last):\n")
  124. list[len(list):] = traceback.format_exception_only(type, value)
  125. finally:
  126. tblist = tb = None
  127. map(self.write, list)
  128. def write(self, data):
  129. """Write a string.
  130. The base implementation writes to sys.stderr; a subclass may
  131. replace this with a different implementation.
  132. """
  133. sys.stderr.write(data)
  134. class InteractiveConsole(InteractiveInterpreter):
  135. """Closely emulate the behavior of the interactive Python interpreter.
  136. This class builds on InteractiveInterpreter and adds prompting
  137. using the familiar sys.ps1 and sys.ps2, and input buffering.
  138. """
  139. def __init__(self, locals=None, filename="<console>"):
  140. """Constructor.
  141. The optional locals argument will be passed to the
  142. InteractiveInterpreter base class.
  143. The optional filename argument should specify the (file)name
  144. of the input stream; it will show up in tracebacks.
  145. """
  146. InteractiveInterpreter.__init__(self, locals)
  147. self.filename = filename
  148. self.resetbuffer()
  149. def resetbuffer(self):
  150. """Reset the input buffer."""
  151. self.buffer = []
  152. def interact(self, banner=None):
  153. """Closely emulate the interactive Python console.
  154. The optional banner argument specify the banner to print
  155. before the first interaction; by default it prints a banner
  156. similar to the one printed by the real Python interpreter,
  157. followed by the current class name in parentheses (so as not
  158. to confuse this with the real interpreter -- since it's so
  159. close!).
  160. """
  161. try:
  162. sys.ps1
  163. except AttributeError:
  164. sys.ps1 = ">>> "
  165. try:
  166. sys.ps2
  167. except AttributeError:
  168. sys.ps2 = "... "
  169. cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
  170. if banner is None:
  171. self.write("Python %s on %s\n%s\n(%s)\n" %
  172. (sys.version, sys.platform, cprt,
  173. self.__class__.__name__))
  174. else:
  175. self.write("%s\n" % str(banner))
  176. more = 0
  177. while 1:
  178. try:
  179. if more:
  180. prompt = sys.ps2
  181. else:
  182. prompt = sys.ps1
  183. try:
  184. line = self.raw_input(prompt)
  185. # Can be None if sys.stdin was redefined
  186. encoding = getattr(sys.stdin, "encoding", None)
  187. if encoding and not isinstance(line, unicode):
  188. line = line.decode(encoding)
  189. except EOFError:
  190. self.write("\n")
  191. break
  192. else:
  193. more = self.push(line)
  194. except KeyboardInterrupt:
  195. self.write("\nKeyboardInterrupt\n")
  196. self.resetbuffer()
  197. more = 0
  198. def push(self, line):
  199. """Push a line to the interpreter.
  200. The line should not have a trailing newline; it may have
  201. internal newlines. The line is appended to a buffer and the
  202. interpreter's runsource() method is called with the
  203. concatenated contents of the buffer as source. If this
  204. indicates that the command was executed or invalid, the buffer
  205. is reset; otherwise, the command is incomplete, and the buffer
  206. is left as it was after the line was appended. The return
  207. value is 1 if more input is required, 0 if the line was dealt
  208. with in some way (this is the same as runsource()).
  209. """
  210. self.buffer.append(line)
  211. source = "\n".join(self.buffer)
  212. more = self.runsource(source, self.filename)
  213. if not more:
  214. self.resetbuffer()
  215. return more
  216. def raw_input(self, prompt=""):
  217. """Write a prompt and read a line.
  218. The returned line does not include the trailing newline.
  219. When the user enters the EOF key sequence, EOFError is raised.
  220. The base implementation uses the built-in function
  221. raw_input(); a subclass may replace this with a different
  222. implementation.
  223. """
  224. return raw_input(prompt)
  225. def interact(banner=None, readfunc=None, local=None):
  226. """Closely emulate the interactive Python interpreter.
  227. This is a backwards compatible interface to the InteractiveConsole
  228. class. When readfunc is not specified, it attempts to import the
  229. readline module to enable GNU readline if it is available.
  230. Arguments (all optional, all default to None):
  231. banner -- passed to InteractiveConsole.interact()
  232. readfunc -- if not None, replaces InteractiveConsole.raw_input()
  233. local -- passed to InteractiveInterpreter.__init__()
  234. """
  235. console = InteractiveConsole(local)
  236. if readfunc is not None:
  237. console.raw_input = readfunc
  238. else:
  239. try:
  240. import readline
  241. except ImportError:
  242. pass
  243. console.interact(banner)
  244. if __name__ == "__main__":
  245. interact()