/Lib/cgitb.py

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