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.

314 lines
10 KiB

Merged revisions 56492-56752 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/p3yk ........ r56497 | kurt.kaiser | 2007-07-22 14:55:16 -0700 (Sun, 22 Jul 2007) | 4 lines In the case of syntax errors, in py3k format_exception_only() was including line number and position in the final line of the exception notification, duplicating info in previous lines. ........ r56501 | kurt.kaiser | 2007-07-22 19:35:50 -0700 (Sun, 22 Jul 2007) | 2 lines Hum, needed a newline in the last change. ........ r56536 | kurt.kaiser | 2007-07-24 19:06:48 -0700 (Tue, 24 Jul 2007) | 5 lines Not all instantiations of SyntaxError set the args attribute. e.g. symtable.c Modify format_exception_only() to get SyntaxError attributes directly instead of unpacking 'args'. ........ r56537 | kurt.kaiser | 2007-07-24 19:13:03 -0700 (Tue, 24 Jul 2007) | 3 lines Update doctest strings: traceback.py no longer prints redundant location information in the last line of the exception display. ........ r56627 | kurt.kaiser | 2007-07-29 21:06:57 -0700 (Sun, 29 Jul 2007) | 2 lines Interactive interpreter emulator (code.py) failing to print exceptions. ........ r56628 | kurt.kaiser | 2007-07-29 21:41:02 -0700 (Sun, 29 Jul 2007) | 2 lines Eliminate extra lines before and after tracebacks. ........ r56638 | kurt.kaiser | 2007-07-31 19:36:45 -0700 (Tue, 31 Jul 2007) | 3 lines Refactor syntax error display in shell and edit windows; move colorize_syntax_error() to EditorWindow; update to py3k. ........ r56685 | neal.norwitz | 2007-08-02 22:20:23 -0700 (Thu, 02 Aug 2007) | 10 lines Remove several h/w and o/s specific modules that are undocumented, obsolete, and/or not widely used: linuxaudiodev.c, sunaudiodev.c Lib/plat-sunos5/SUNAUDIODEV.py Lib/audiodev.py Tools/audiopy/audiopy Move Lib/toaiff.py to Demo. See PEP 3108 for most of the details. ........ r56686 | neal.norwitz | 2007-08-02 22:21:48 -0700 (Thu, 02 Aug 2007) | 4 lines Missed one module that should have been removed since it relied on audiodev which was removed. ........ r56748 | neal.norwitz | 2007-08-04 19:19:04 -0700 (Sat, 04 Aug 2007) | 1 line Make from X import * outside module scope an error. ........ r56750 | neal.norwitz | 2007-08-04 19:35:01 -0700 (Sat, 04 Aug 2007) | 1 line Use READONLY consistently instead of RO ........
19 years ago
Merged revisions 56492-56752 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/p3yk ........ r56497 | kurt.kaiser | 2007-07-22 14:55:16 -0700 (Sun, 22 Jul 2007) | 4 lines In the case of syntax errors, in py3k format_exception_only() was including line number and position in the final line of the exception notification, duplicating info in previous lines. ........ r56501 | kurt.kaiser | 2007-07-22 19:35:50 -0700 (Sun, 22 Jul 2007) | 2 lines Hum, needed a newline in the last change. ........ r56536 | kurt.kaiser | 2007-07-24 19:06:48 -0700 (Tue, 24 Jul 2007) | 5 lines Not all instantiations of SyntaxError set the args attribute. e.g. symtable.c Modify format_exception_only() to get SyntaxError attributes directly instead of unpacking 'args'. ........ r56537 | kurt.kaiser | 2007-07-24 19:13:03 -0700 (Tue, 24 Jul 2007) | 3 lines Update doctest strings: traceback.py no longer prints redundant location information in the last line of the exception display. ........ r56627 | kurt.kaiser | 2007-07-29 21:06:57 -0700 (Sun, 29 Jul 2007) | 2 lines Interactive interpreter emulator (code.py) failing to print exceptions. ........ r56628 | kurt.kaiser | 2007-07-29 21:41:02 -0700 (Sun, 29 Jul 2007) | 2 lines Eliminate extra lines before and after tracebacks. ........ r56638 | kurt.kaiser | 2007-07-31 19:36:45 -0700 (Tue, 31 Jul 2007) | 3 lines Refactor syntax error display in shell and edit windows; move colorize_syntax_error() to EditorWindow; update to py3k. ........ r56685 | neal.norwitz | 2007-08-02 22:20:23 -0700 (Thu, 02 Aug 2007) | 10 lines Remove several h/w and o/s specific modules that are undocumented, obsolete, and/or not widely used: linuxaudiodev.c, sunaudiodev.c Lib/plat-sunos5/SUNAUDIODEV.py Lib/audiodev.py Tools/audiopy/audiopy Move Lib/toaiff.py to Demo. See PEP 3108 for most of the details. ........ r56686 | neal.norwitz | 2007-08-02 22:21:48 -0700 (Thu, 02 Aug 2007) | 4 lines Missed one module that should have been removed since it relied on audiodev which was removed. ........ r56748 | neal.norwitz | 2007-08-04 19:19:04 -0700 (Sat, 04 Aug 2007) | 1 line Make from X import * outside module scope an error. ........ r56750 | neal.norwitz | 2007-08-04 19:35:01 -0700 (Sat, 04 Aug 2007) | 1 line Use READONLY consistently instead of RO ........
19 years ago
Merged revisions 75264,75268,75293,75318,75391-75392,75436,75478,75971,76003,76058,76140-76141,76231,76380,76428-76429 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r75264 | andrew.kuchling | 2009-10-05 17:30:22 -0500 (Mon, 05 Oct 2009) | 1 line Add various items ........ r75268 | andrew.kuchling | 2009-10-05 17:45:39 -0500 (Mon, 05 Oct 2009) | 1 line Remove two notes ........ r75293 | kristjan.jonsson | 2009-10-09 09:32:19 -0500 (Fri, 09 Oct 2009) | 2 lines http://bugs.python.org/issue7029 a non-default timer wasn't actually used by the individual Tests. ........ r75318 | benjamin.peterson | 2009-10-10 16:15:58 -0500 (Sat, 10 Oct 2009) | 1 line remove script which uses long gone module ........ r75391 | andrew.kuchling | 2009-10-13 10:49:33 -0500 (Tue, 13 Oct 2009) | 1 line Link to PEP ........ r75392 | andrew.kuchling | 2009-10-13 11:11:49 -0500 (Tue, 13 Oct 2009) | 1 line Various link, textual, and markup fixes ........ r75436 | benjamin.peterson | 2009-10-15 10:39:15 -0500 (Thu, 15 Oct 2009) | 1 line don't need to mess up sys.path ........ r75478 | senthil.kumaran | 2009-10-17 20:58:45 -0500 (Sat, 17 Oct 2009) | 3 lines Fix a typo. ........ r75971 | benjamin.peterson | 2009-10-30 22:56:15 -0500 (Fri, 30 Oct 2009) | 1 line add some checks for evaluation order with parenthesis #7210 ........ r76003 | antoine.pitrou | 2009-10-31 19:30:13 -0500 (Sat, 31 Oct 2009) | 6 lines Hopefully fix the buildbot problems on test_mailbox, by computing the maildir toc cache refresh date before actually refreshing the cache. (see #6896) ........ r76058 | benjamin.peterson | 2009-11-02 10:14:19 -0600 (Mon, 02 Nov 2009) | 1 line grant list.index() a more informative error message #7252 ........ r76140 | nick.coghlan | 2009-11-07 02:13:55 -0600 (Sat, 07 Nov 2009) | 1 line Add test for runpy.run_module package execution and use something other than logging as the example of a non-executable package ........ r76141 | nick.coghlan | 2009-11-07 02:15:01 -0600 (Sat, 07 Nov 2009) | 1 line Some minor cleanups to private runpy code and docstrings ........ r76231 | benjamin.peterson | 2009-11-12 17:42:23 -0600 (Thu, 12 Nov 2009) | 1 line this main is much more useful ........ r76380 | antoine.pitrou | 2009-11-18 14:20:46 -0600 (Wed, 18 Nov 2009) | 3 lines Mention Giampolo R's new FTP TLS support in the what's new file ........ r76428 | benjamin.peterson | 2009-11-19 20:15:50 -0600 (Thu, 19 Nov 2009) | 1 line turn goto into do while loop ........ r76429 | benjamin.peterson | 2009-11-19 20:56:43 -0600 (Thu, 19 Nov 2009) | 2 lines avoid doing an uneeded import in a function ........
16 years ago
  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, exitmsg=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. The optional exitmsg argument specifies the exit message
  151. printed when exiting. Pass the empty string to suppress
  152. printing an exit message. If exitmsg is not given or None,
  153. a default message is printed.
  154. """
  155. try:
  156. sys.ps1
  157. except AttributeError:
  158. sys.ps1 = ">>> "
  159. try:
  160. sys.ps2
  161. except AttributeError:
  162. sys.ps2 = "... "
  163. cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
  164. if banner is None:
  165. self.write("Python %s on %s\n%s\n(%s)\n" %
  166. (sys.version, sys.platform, cprt,
  167. self.__class__.__name__))
  168. elif banner:
  169. self.write("%s\n" % str(banner))
  170. more = 0
  171. while 1:
  172. try:
  173. if more:
  174. prompt = sys.ps2
  175. else:
  176. prompt = sys.ps1
  177. try:
  178. line = self.raw_input(prompt)
  179. except EOFError:
  180. self.write("\n")
  181. break
  182. else:
  183. more = self.push(line)
  184. except KeyboardInterrupt:
  185. self.write("\nKeyboardInterrupt\n")
  186. self.resetbuffer()
  187. more = 0
  188. if exitmsg is None:
  189. self.write('now exiting %s...\n' % self.__class__.__name__)
  190. elif exitmsg != '':
  191. self.write('%s\n' % exitmsg)
  192. def push(self, line):
  193. """Push a line to the interpreter.
  194. The line should not have a trailing newline; it may have
  195. internal newlines. The line is appended to a buffer and the
  196. interpreter's runsource() method is called with the
  197. concatenated contents of the buffer as source. If this
  198. indicates that the command was executed or invalid, the buffer
  199. is reset; otherwise, the command is incomplete, and the buffer
  200. is left as it was after the line was appended. The return
  201. value is 1 if more input is required, 0 if the line was dealt
  202. with in some way (this is the same as runsource()).
  203. """
  204. self.buffer.append(line)
  205. source = "\n".join(self.buffer)
  206. more = self.runsource(source, self.filename)
  207. if not more:
  208. self.resetbuffer()
  209. return more
  210. def raw_input(self, prompt=""):
  211. """Write a prompt and read a line.
  212. The returned line does not include the trailing newline.
  213. When the user enters the EOF key sequence, EOFError is raised.
  214. The base implementation uses the built-in function
  215. input(); a subclass may replace this with a different
  216. implementation.
  217. """
  218. return input(prompt)
  219. def interact(banner=None, readfunc=None, local=None, exitmsg=None):
  220. """Closely emulate the interactive Python interpreter.
  221. This is a backwards compatible interface to the InteractiveConsole
  222. class. When readfunc is not specified, it attempts to import the
  223. readline module to enable GNU readline if it is available.
  224. Arguments (all optional, all default to None):
  225. banner -- passed to InteractiveConsole.interact()
  226. readfunc -- if not None, replaces InteractiveConsole.raw_input()
  227. local -- passed to InteractiveInterpreter.__init__()
  228. exitmsg -- passed to InteractiveConsole.interact()
  229. """
  230. console = InteractiveConsole(local)
  231. if readfunc is not None:
  232. console.raw_input = readfunc
  233. else:
  234. try:
  235. import readline
  236. except ImportError:
  237. pass
  238. console.interact(banner, exitmsg)
  239. if __name__ == "__main__":
  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)