code.py 9.9 KB

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