code.py 11 KB

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