PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/cgitb.py

https://bitbucket.org/dac_io/pypy
Python | 318 lines | 307 code | 0 blank | 11 comment | 0 complexity | 0b8e18e77bb6aec9ae9bc6b0df188284 MD5 | raw file
  1. """More comprehensive traceback formatting for Python scripts.
  2. To enable this module, do:
  3. import cgitb; cgitb.enable()
  4. at the top of your script. The optional arguments to enable() are:
  5. display - if true, tracebacks are displayed in the web browser
  6. logdir - if set, tracebacks are written to files in this directory
  7. context - number of lines of source code to show for each stack frame
  8. format - 'text' or 'html' controls the output format
  9. By default, tracebacks are displayed but not saved, the context is 5 lines
  10. and the output format is 'html' (for backwards compatibility with the
  11. original use of this module)
  12. Alternatively, if you have caught an exception and want cgitb to display it
  13. for you, call cgitb.handler(). The optional argument to handler() is a
  14. 3-item tuple (etype, evalue, etb) just like the value of sys.exc_info().
  15. The default handler displays output as HTML.
  16. """
  17. import inspect
  18. import keyword
  19. import linecache
  20. import os
  21. import pydoc
  22. import sys
  23. import tempfile
  24. import time
  25. import tokenize
  26. import traceback
  27. import types
  28. def reset():
  29. """Return a string that resets the CGI and browser to a known state."""
  30. return '''<!--: spam
  31. Content-Type: text/html
  32. <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
  33. <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
  34. </font> </font> </font> </script> </object> </blockquote> </pre>
  35. </table> </table> </table> </table> </table> </font> </font> </font>'''
  36. __UNDEF__ = [] # a special sentinel object
  37. def small(text):
  38. if text:
  39. return '<small>' + text + '</small>'
  40. else:
  41. return ''
  42. def strong(text):
  43. if text:
  44. return '<strong>' + text + '</strong>'
  45. else:
  46. return ''
  47. def grey(text):
  48. if text:
  49. return '<font color="#909090">' + text + '</font>'
  50. else:
  51. return ''
  52. def lookup(name, frame, locals):
  53. """Find the value for a given name in the given environment."""
  54. if name in locals:
  55. return 'local', locals[name]
  56. if name in frame.f_globals:
  57. return 'global', frame.f_globals[name]
  58. if '__builtins__' in frame.f_globals:
  59. builtins = frame.f_globals['__builtins__']
  60. if type(builtins) is type({}):
  61. if name in builtins:
  62. return 'builtin', builtins[name]
  63. else:
  64. if hasattr(builtins, name):
  65. return 'builtin', getattr(builtins, name)
  66. return None, __UNDEF__
  67. def scanvars(reader, frame, locals):
  68. """Scan one logical line of Python and look up values of variables used."""
  69. vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
  70. for ttype, token, start, end, line in tokenize.generate_tokens(reader):
  71. if ttype == tokenize.NEWLINE: break
  72. if ttype == tokenize.NAME and token not in keyword.kwlist:
  73. if lasttoken == '.':
  74. if parent is not __UNDEF__:
  75. value = getattr(parent, token, __UNDEF__)
  76. vars.append((prefix + token, prefix, value))
  77. else:
  78. where, value = lookup(token, frame, locals)
  79. vars.append((token, where, value))
  80. elif token == '.':
  81. prefix += lasttoken + '.'
  82. parent = value
  83. else:
  84. parent, prefix = None, ''
  85. lasttoken = token
  86. return vars
  87. def html(einfo, context=5):
  88. """Return a nice HTML document describing a given traceback."""
  89. etype, evalue, etb = einfo
  90. if type(etype) is types.ClassType:
  91. etype = etype.__name__
  92. pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
  93. date = time.ctime(time.time())
  94. head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
  95. '<big><big>%s</big></big>' %
  96. strong(pydoc.html.escape(str(etype))),
  97. '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
  98. <p>A problem occurred in a Python script. Here is the sequence of
  99. function calls leading up to the error, in the order they occurred.</p>'''
  100. indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
  101. frames = []
  102. records = inspect.getinnerframes(etb, context)
  103. for frame, file, lnum, func, lines, index in records:
  104. if file:
  105. file = os.path.abspath(file)
  106. link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
  107. else:
  108. file = link = '?'
  109. args, varargs, varkw, locals = inspect.getargvalues(frame)
  110. call = ''
  111. if func != '?':
  112. call = 'in ' + strong(func) + \
  113. inspect.formatargvalues(args, varargs, varkw, locals,
  114. formatvalue=lambda value: '=' + pydoc.html.repr(value))
  115. highlight = {}
  116. def reader(lnum=[lnum]):
  117. highlight[lnum[0]] = 1
  118. try: return linecache.getline(file, lnum[0])
  119. finally: lnum[0] += 1
  120. vars = scanvars(reader, frame, locals)
  121. rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
  122. ('<big>&nbsp;</big>', link, call)]
  123. if index is not None:
  124. i = lnum - index
  125. for line in lines:
  126. num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
  127. if i in highlight:
  128. line = '<tt>=&gt;%s%s</tt>' % (num, pydoc.html.preformat(line))
  129. rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
  130. else:
  131. line = '<tt>&nbsp;&nbsp;%s%s</tt>' % (num, pydoc.html.preformat(line))
  132. rows.append('<tr><td>%s</td></tr>' % grey(line))
  133. i += 1
  134. done, dump = {}, []
  135. for name, where, value in vars:
  136. if name in done: continue
  137. done[name] = 1
  138. if value is not __UNDEF__:
  139. if where in ('global', 'builtin'):
  140. name = ('<em>%s</em> ' % where) + strong(name)
  141. elif where == 'local':
  142. name = strong(name)
  143. else:
  144. name = where + strong(name.split('.')[-1])
  145. dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
  146. else:
  147. dump.append(name + ' <em>undefined</em>')
  148. rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
  149. frames.append('''
  150. <table width="100%%" cellspacing=0 cellpadding=0 border=0>
  151. %s</table>''' % '\n'.join(rows))
  152. exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
  153. pydoc.html.escape(str(evalue)))]
  154. if isinstance(evalue, BaseException):
  155. for name in dir(evalue):
  156. if name[:1] == '_': continue
  157. value = pydoc.html.repr(getattr(evalue, name))
  158. exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
  159. return head + ''.join(frames) + ''.join(exception) + '''
  160. <!-- The above is a description of an error in a Python program, formatted
  161. for a Web browser because the 'cgitb' module was enabled. In case you
  162. are not reading this in a Web browser, here is the original traceback:
  163. %s
  164. -->
  165. ''' % pydoc.html.escape(
  166. ''.join(traceback.format_exception(etype, evalue, etb)))
  167. def text(einfo, context=5):
  168. """Return a plain text document describing a given traceback."""
  169. etype, evalue, etb = einfo
  170. if type(etype) is types.ClassType:
  171. etype = etype.__name__
  172. pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
  173. date = time.ctime(time.time())
  174. head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
  175. A problem occurred in a Python script. Here is the sequence of
  176. function calls leading up to the error, in the order they occurred.
  177. '''
  178. frames = []
  179. records = inspect.getinnerframes(etb, context)
  180. for frame, file, lnum, func, lines, index in records:
  181. file = file and os.path.abspath(file) or '?'
  182. args, varargs, varkw, locals = inspect.getargvalues(frame)
  183. call = ''
  184. if func != '?':
  185. call = 'in ' + func + \
  186. inspect.formatargvalues(args, varargs, varkw, locals,
  187. formatvalue=lambda value: '=' + pydoc.text.repr(value))
  188. highlight = {}
  189. def reader(lnum=[lnum]):
  190. highlight[lnum[0]] = 1
  191. try: return linecache.getline(file, lnum[0])
  192. finally: lnum[0] += 1
  193. vars = scanvars(reader, frame, locals)
  194. rows = [' %s %s' % (file, call)]
  195. if index is not None:
  196. i = lnum - index
  197. for line in lines:
  198. num = '%5d ' % i
  199. rows.append(num+line.rstrip())
  200. i += 1
  201. done, dump = {}, []
  202. for name, where, value in vars:
  203. if name in done: continue
  204. done[name] = 1
  205. if value is not __UNDEF__:
  206. if where == 'global': name = 'global ' + name
  207. elif where != 'local': name = where + name.split('.')[-1]
  208. dump.append('%s = %s' % (name, pydoc.text.repr(value)))
  209. else:
  210. dump.append(name + ' undefined')
  211. rows.append('\n'.join(dump))
  212. frames.append('\n%s\n' % '\n'.join(rows))
  213. exception = ['%s: %s' % (str(etype), str(evalue))]
  214. if isinstance(evalue, BaseException):
  215. for name in dir(evalue):
  216. value = pydoc.text.repr(getattr(evalue, name))
  217. exception.append('\n%s%s = %s' % (" "*4, name, value))
  218. return head + ''.join(frames) + ''.join(exception) + '''
  219. The above is a description of an error in a Python program. Here is
  220. the original traceback:
  221. %s
  222. ''' % ''.join(traceback.format_exception(etype, evalue, etb))
  223. class Hook:
  224. """A hook to replace sys.excepthook that shows tracebacks in HTML."""
  225. def __init__(self, display=1, logdir=None, context=5, file=None,
  226. format="html"):
  227. self.display = display # send tracebacks to browser if true
  228. self.logdir = logdir # log tracebacks to files if not None
  229. self.context = context # number of source code lines per frame
  230. self.file = file or sys.stdout # place to send the output
  231. self.format = format
  232. def __call__(self, etype, evalue, etb):
  233. self.handle((etype, evalue, etb))
  234. def handle(self, info=None):
  235. info = info or sys.exc_info()
  236. if self.format == "html":
  237. self.file.write(reset())
  238. formatter = (self.format=="html") and html or text
  239. plain = False
  240. try:
  241. doc = formatter(info, self.context)
  242. except: # just in case something goes wrong
  243. doc = ''.join(traceback.format_exception(*info))
  244. plain = True
  245. if self.display:
  246. if plain:
  247. doc = doc.replace('&', '&amp;').replace('<', '&lt;')
  248. self.file.write('<pre>' + doc + '</pre>\n')
  249. else:
  250. self.file.write(doc + '\n')
  251. else:
  252. self.file.write('<p>A problem occurred in a Python script.\n')
  253. if self.logdir is not None:
  254. suffix = ['.txt', '.html'][self.format=="html"]
  255. (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
  256. try:
  257. file = os.fdopen(fd, 'w')
  258. file.write(doc)
  259. file.close()
  260. msg = '<p> %s contains the description of this error.' % path
  261. except:
  262. msg = '<p> Tried to save traceback to %s, but failed.' % path
  263. self.file.write(msg + '\n')
  264. try:
  265. self.file.flush()
  266. except: pass
  267. handler = Hook().handle
  268. def enable(display=1, logdir=None, context=5, format="html"):
  269. """Install an exception handler that formats tracebacks as HTML.
  270. The optional argument 'display' can be set to 0 to suppress sending the
  271. traceback to the browser, and 'logdir' can be set to a directory to cause
  272. tracebacks to be written to files there."""
  273. sys.excepthook = Hook(display=display, logdir=logdir,
  274. context=context, format=format)