code.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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_type = type
  80. sys.last_value = value
  81. sys.last_traceback = tb
  82. if filename and type is SyntaxError:
  83. # Work hard to stuff the correct filename in the exception
  84. try:
  85. msg, (dummy_filename, lineno, offset, line) = value.args
  86. except ValueError:
  87. # Not the format we expect; leave it alone
  88. pass
  89. else:
  90. # Stuff in the right filename
  91. value = SyntaxError(msg, (filename, lineno, offset, line))
  92. sys.last_value = value
  93. if sys.excepthook is sys.__excepthook__:
  94. lines = traceback.format_exception_only(type, value)
  95. self.write(''.join(lines))
  96. else:
  97. # If someone has set sys.excepthook, we let that take precedence
  98. # over self.write
  99. sys.excepthook(type, value, tb)
  100. def showtraceback(self):
  101. """Display the exception that just occurred.
  102. We remove the first stack item because it is our own code.
  103. The output is written by self.write(), below.
  104. """
  105. sys.last_type, sys.last_value, last_tb = ei = sys.exc_info()
  106. sys.last_traceback = last_tb
  107. try:
  108. lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next)
  109. if sys.excepthook is sys.__excepthook__:
  110. self.write(''.join(lines))
  111. else:
  112. # If someone has set sys.excepthook, we let that take precedence
  113. # over self.write
  114. sys.excepthook(ei[0], ei[1], last_tb)
  115. finally:
  116. last_tb = ei = None
  117. def write(self, data):
  118. """Write a string.
  119. The base implementation writes to sys.stderr; a subclass may
  120. replace this with a different implementation.
  121. """
  122. sys.stderr.write(data)
  123. class InteractiveConsole(InteractiveInterpreter):
  124. """Closely emulate the behavior of the interactive Python interpreter.
  125. This class builds on InteractiveInterpreter and adds prompting
  126. using the familiar sys.ps1 and sys.ps2, and input buffering.
  127. """
  128. def __init__(self, locals=None, filename="<console>"):
  129. """Constructor.
  130. The optional locals argument will be passed to the
  131. InteractiveInterpreter base class.
  132. The optional filename argument should specify the (file)name
  133. of the input stream; it will show up in tracebacks.
  134. """
  135. InteractiveInterpreter.__init__(self, locals)
  136. self.filename = filename
  137. self.resetbuffer()
  138. def resetbuffer(self):
  139. """Reset the input buffer."""
  140. self.buffer = []
  141. def interact(self, banner=None, exitmsg=None):
  142. """Closely emulate the interactive Python console.
  143. The optional banner argument specifies the banner to print
  144. before the first interaction; by default it prints a banner
  145. similar to the one printed by the real Python interpreter,
  146. followed by the current class name in parentheses (so as not
  147. to confuse this with the real interpreter -- since it's so
  148. close!).
  149. The optional exitmsg argument specifies the exit message
  150. printed when exiting. Pass the empty string to suppress
  151. printing an exit message. If exitmsg is not given or None,
  152. a default message is printed.
  153. """
  154. try:
  155. sys.ps1
  156. except AttributeError:
  157. sys.ps1 = ">>> "
  158. try:
  159. sys.ps2
  160. except AttributeError:
  161. sys.ps2 = "... "
  162. cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
  163. if banner is None:
  164. self.write("Python %s on %s\n%s\n(%s)\n" %
  165. (sys.version, sys.platform, cprt,
  166. self.__class__.__name__))
  167. elif banner:
  168. self.write("%s\n" % str(banner))
  169. more = 0
  170. while 1:
  171. try:
  172. if more:
  173. prompt = sys.ps2
  174. else:
  175. prompt = sys.ps1
  176. try:
  177. line = self.raw_input(prompt)
  178. except EOFError:
  179. self.write("\n")
  180. break
  181. else:
  182. more = self.push(line)
  183. except KeyboardInterrupt:
  184. self.write("\nKeyboardInterrupt\n")
  185. self.resetbuffer()
  186. more = 0
  187. if exitmsg is None:
  188. self.write('now exiting %s...\n' % self.__class__.__name__)
  189. elif exitmsg != '':
  190. self.write('%s\n' % exitmsg)
  191. def push(self, line):
  192. """Push a line to the interpreter.
  193. The line should not have a trailing newline; it may have
  194. internal newlines. The line is appended to a buffer and the
  195. interpreter's runsource() method is called with the
  196. concatenated contents of the buffer as source. If this
  197. indicates that the command was executed or invalid, the buffer
  198. is reset; otherwise, the command is incomplete, and the buffer
  199. is left as it was after the line was appended. The return
  200. value is 1 if more input is required, 0 if the line was dealt
  201. with in some way (this is the same as runsource()).
  202. """
  203. self.buffer.append(line)
  204. source = "\n".join(self.buffer)
  205. more = self.runsource(source, self.filename)
  206. if not more:
  207. self.resetbuffer()
  208. return more
  209. def raw_input(self, prompt=""):
  210. """Write a prompt and read a line.
  211. The returned line does not include the trailing newline.
  212. When the user enters the EOF key sequence, EOFError is raised.
  213. The base implementation uses the built-in function
  214. input(); a subclass may replace this with a different
  215. implementation.
  216. """
  217. return input(prompt)
  218. def interact(banner=None, readfunc=None, local=None, exitmsg=None):
  219. """Closely emulate the interactive Python interpreter.
  220. This is a backwards compatible interface to the InteractiveConsole
  221. class. When readfunc is not specified, it attempts to import the
  222. readline module to enable GNU readline if it is available.
  223. Arguments (all optional, all default to None):
  224. banner -- passed to InteractiveConsole.interact()
  225. readfunc -- if not None, replaces InteractiveConsole.raw_input()
  226. local -- passed to InteractiveInterpreter.__init__()
  227. exitmsg -- passed to InteractiveConsole.interact()
  228. """
  229. console = InteractiveConsole(local)
  230. if readfunc is not None:
  231. console.raw_input = readfunc
  232. else:
  233. try:
  234. import readline
  235. except ImportError:
  236. pass
  237. console.interact(banner, exitmsg)
  238. if __name__ == "__main__":
  239. import argparse
  240. parser = argparse.ArgumentParser()
  241. parser.add_argument('-q', action='store_true',
  242. help="don't print version and copyright messages")
  243. args = parser.parse_args()
  244. if args.q or sys.flags.quiet:
  245. banner = ''
  246. else:
  247. banner = None
  248. interact(banner)