You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

code.py 10KB

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