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.

302 lines
9.8 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 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. 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 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. try:
  106. type, value, tb = sys.exc_info()
  107. sys.last_type = type
  108. sys.last_value = value
  109. sys.last_traceback = tb
  110. tblist = traceback.extract_tb(tb)
  111. del tblist[:1]
  112. lines = traceback.format_list(tblist)
  113. if lines:
  114. lines.insert(0, "Traceback (most recent call last):\n")
  115. lines.extend(traceback.format_exception_only(type, value))
  116. finally:
  117. tblist = tb = None
  118. if sys.excepthook is sys.__excepthook__:
  119. self.write(''.join(lines))
  120. else:
  121. # If someone has set sys.excepthook, we let that take precedence
  122. # over self.write
  123. sys.excepthook(type, value, tb)
  124. def write(self, data):
  125. """Write a string.
  126. The base implementation writes to sys.stderr; a subclass may
  127. replace this with a different implementation.
  128. """
  129. sys.stderr.write(data)
  130. class InteractiveConsole(InteractiveInterpreter):
  131. """Closely emulate the behavior of the interactive Python interpreter.
  132. This class builds on InteractiveInterpreter and adds prompting
  133. using the familiar sys.ps1 and sys.ps2, and input buffering.
  134. """
  135. def __init__(self, locals=None, filename="<console>"):
  136. """Constructor.
  137. The optional locals argument will be passed to the
  138. InteractiveInterpreter base class.
  139. The optional filename argument should specify the (file)name
  140. of the input stream; it will show up in tracebacks.
  141. """
  142. InteractiveInterpreter.__init__(self, locals)
  143. self.filename = filename
  144. self.resetbuffer()
  145. def resetbuffer(self):
  146. """Reset the input buffer."""
  147. self.buffer = []
  148. def interact(self, banner=None):
  149. """Closely emulate the interactive Python console.
  150. The optional banner argument specifies the banner to print
  151. before the first interaction; by default it prints a banner
  152. similar to the one printed by the real Python interpreter,
  153. followed by the current class name in parentheses (so as not
  154. to confuse this with the real interpreter -- since it's so
  155. close!).
  156. """
  157. try:
  158. sys.ps1
  159. except AttributeError:
  160. sys.ps1 = ">>> "
  161. try:
  162. sys.ps2
  163. except AttributeError:
  164. sys.ps2 = "... "
  165. cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
  166. if banner is None:
  167. self.write("Python %s on %s\n%s\n(%s)\n" %
  168. (sys.version, sys.platform, cprt,
  169. self.__class__.__name__))
  170. else:
  171. self.write("%s\n" % str(banner))
  172. more = 0
  173. while 1:
  174. try:
  175. if more:
  176. prompt = sys.ps2
  177. else:
  178. prompt = sys.ps1
  179. try:
  180. line = self.raw_input(prompt)
  181. except EOFError:
  182. self.write("\n")
  183. break
  184. else:
  185. more = self.push(line)
  186. except KeyboardInterrupt:
  187. self.write("\nKeyboardInterrupt\n")
  188. self.resetbuffer()
  189. more = 0
  190. def push(self, line):
  191. """Push a line to the interpreter.
  192. The line should not have a trailing newline; it may have
  193. internal newlines. The line is appended to a buffer and the
  194. interpreter's runsource() method is called with the
  195. concatenated contents of the buffer as source. If this
  196. indicates that the command was executed or invalid, the buffer
  197. is reset; otherwise, the command is incomplete, and the buffer
  198. is left as it was after the line was appended. The return
  199. value is 1 if more input is required, 0 if the line was dealt
  200. with in some way (this is the same as runsource()).
  201. """
  202. self.buffer.append(line)
  203. source = "\n".join(self.buffer)
  204. more = self.runsource(source, self.filename)
  205. if not more:
  206. self.resetbuffer()
  207. return more
  208. def raw_input(self, prompt=""):
  209. """Write a prompt and read a line.
  210. The returned line does not include the trailing newline.
  211. When the user enters the EOF key sequence, EOFError is raised.
  212. The base implementation uses the built-in function
  213. input(); a subclass may replace this with a different
  214. implementation.
  215. """
  216. return input(prompt)
  217. def interact(banner=None, readfunc=None, local=None):
  218. """Closely emulate the interactive Python interpreter.
  219. This is a backwards compatible interface to the InteractiveConsole
  220. class. When readfunc is not specified, it attempts to import the
  221. readline module to enable GNU readline if it is available.
  222. Arguments (all optional, all default to None):
  223. banner -- passed to InteractiveConsole.interact()
  224. readfunc -- if not None, replaces InteractiveConsole.raw_input()
  225. local -- passed to InteractiveInterpreter.__init__()
  226. """
  227. console = InteractiveConsole(local)
  228. if readfunc is not None:
  229. console.raw_input = readfunc
  230. else:
  231. try:
  232. import readline
  233. except ImportError:
  234. pass
  235. console.interact(banner)
  236. if __name__ == "__main__":
  237. interact()