cgitb.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. def reset():
  28. """Return a string that resets the CGI and browser to a known state."""
  29. return '''<!--: spam
  30. Content-Type: text/html
  31. <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
  32. <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
  33. </font> </font> </font> </script> </object> </blockquote> </pre>
  34. </table> </table> </table> </table> </table> </font> </font> </font>'''
  35. __UNDEF__ = [] # a special sentinel object
  36. def small(text):
  37. if text:
  38. return '<small>' + text + '</small>'
  39. else:
  40. return ''
  41. def strong(text):
  42. if text:
  43. return '<strong>' + text + '</strong>'
  44. else:
  45. return ''
  46. def grey(text):
  47. if text:
  48. return '<font color="#909090">' + text + '</font>'
  49. else:
  50. return ''
  51. def lookup(name, frame, locals):
  52. """Find the value for a given name in the given environment."""
  53. if name in locals:
  54. return 'local', locals[name]
  55. if name in frame.f_globals:
  56. return 'global', frame.f_globals[name]
  57. if '__builtins__' in frame.f_globals:
  58. builtins = frame.f_globals['__builtins__']
  59. if type(builtins) is type({}):
  60. if name in builtins:
  61. return 'builtin', builtins[name]
  62. else:
  63. if hasattr(builtins, name):
  64. return 'builtin', getattr(builtins, name)
  65. return None, __UNDEF__
  66. def scanvars(reader, frame, locals):
  67. """Scan one logical line of Python and look up values of variables used."""
  68. vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
  69. for ttype, token, start, end, line in tokenize.generate_tokens(reader):
  70. if ttype == tokenize.NEWLINE: break
  71. if ttype == tokenize.NAME and token not in keyword.kwlist:
  72. if lasttoken == '.':
  73. if parent is not __UNDEF__:
  74. value = getattr(parent, token, __UNDEF__)
  75. vars.append((prefix + token, prefix, value))
  76. else:
  77. where, value = lookup(token, frame, locals)
  78. vars.append((token, where, value))
  79. elif token == '.':
  80. prefix += lasttoken + '.'
  81. parent = value
  82. else:
  83. parent, prefix = None, ''
  84. lasttoken = token
  85. return vars
  86. def html(einfo, context=5):
  87. """Return a nice HTML document describing a given traceback."""
  88. etype, evalue, etb = einfo
  89. if isinstance(etype, type):
  90. etype = etype.__name__
  91. pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
  92. date = time.ctime(time.time())
  93. head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
  94. '<big><big>%s</big></big>' %
  95. strong(pydoc.html.escape(str(etype))),
  96. '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
  97. <p>A problem occurred in a Python script. Here is the sequence of
  98. function calls leading up to the error, in the order they occurred.</p>'''
  99. indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
  100. frames = []
  101. records = inspect.getinnerframes(etb, context)
  102. for frame, file, lnum, func, lines, index in records:
  103. if file:
  104. file = os.path.abspath(file)
  105. link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
  106. else:
  107. file = link = '?'
  108. args, varargs, varkw, locals = inspect.getargvalues(frame)
  109. call = ''
  110. if func != '?':
  111. call = 'in ' + strong(pydoc.html.escape(func))
  112. if func != "<module>":
  113. call += 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. for name in dir(evalue):
  155. if name[:1] == '_': continue
  156. value = pydoc.html.repr(getattr(evalue, name))
  157. exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
  158. return head + ''.join(frames) + ''.join(exception) + '''
  159. <!-- The above is a description of an error in a Python program, formatted
  160. for a Web browser because the 'cgitb' module was enabled. In case you
  161. are not reading this in a Web browser, here is the original traceback:
  162. %s
  163. -->
  164. ''' % pydoc.html.escape(
  165. ''.join(traceback.format_exception(etype, evalue, etb)))
  166. def text(einfo, context=5):
  167. """Return a plain text document describing a given traceback."""
  168. etype, evalue, etb = einfo
  169. if isinstance(etype, type):
  170. etype = etype.__name__
  171. pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
  172. date = time.ctime(time.time())
  173. head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
  174. A problem occurred in a Python script. Here is the sequence of
  175. function calls leading up to the error, in the order they occurred.
  176. '''
  177. frames = []
  178. records = inspect.getinnerframes(etb, context)
  179. for frame, file, lnum, func, lines, index in records:
  180. file = file and os.path.abspath(file) or '?'
  181. args, varargs, varkw, locals = inspect.getargvalues(frame)
  182. call = ''
  183. if func != '?':
  184. call = 'in ' + func
  185. if func != "<module>":
  186. call += 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. for name in dir(evalue):
  215. value = pydoc.text.repr(getattr(evalue, name))
  216. exception.append('\n%s%s = %s' % (" "*4, name, value))
  217. return head + ''.join(frames) + ''.join(exception) + '''
  218. The above is a description of an error in a Python program. Here is
  219. the original traceback:
  220. %s
  221. ''' % ''.join(traceback.format_exception(etype, evalue, etb))
  222. class Hook:
  223. """A hook to replace sys.excepthook that shows tracebacks in HTML."""
  224. def __init__(self, display=1, logdir=None, context=5, file=None,
  225. format="html"):
  226. self.display = display # send tracebacks to browser if true
  227. self.logdir = logdir # log tracebacks to files if not None
  228. self.context = context # number of source code lines per frame
  229. self.file = file or sys.stdout # place to send the output
  230. self.format = format
  231. def __call__(self, etype, evalue, etb):
  232. self.handle((etype, evalue, etb))
  233. def handle(self, info=None):
  234. info = info or sys.exc_info()
  235. if self.format == "html":
  236. self.file.write(reset())
  237. formatter = (self.format=="html") and html or text
  238. plain = False
  239. try:
  240. doc = formatter(info, self.context)
  241. except: # just in case something goes wrong
  242. doc = ''.join(traceback.format_exception(*info))
  243. plain = True
  244. if self.display:
  245. if plain:
  246. doc = pydoc.html.escape(doc)
  247. self.file.write('<pre>' + doc + '</pre>\n')
  248. else:
  249. self.file.write(doc + '\n')
  250. else:
  251. self.file.write('<p>A problem occurred in a Python script.\n')
  252. if self.logdir is not None:
  253. suffix = ['.txt', '.html'][self.format=="html"]
  254. (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
  255. try:
  256. with os.fdopen(fd, 'w') as file:
  257. file.write(doc)
  258. msg = '%s contains the description of this error.' % path
  259. except:
  260. msg = 'Tried to save traceback to %s, but failed.' % path
  261. if self.format == 'html':
  262. self.file.write('<p>%s</p>\n' % msg)
  263. else:
  264. self.file.write(msg + '\n')
  265. try:
  266. self.file.flush()
  267. except: pass
  268. handler = Hook().handle
  269. def enable(display=1, logdir=None, context=5, format="html"):
  270. """Install an exception handler that formats tracebacks as HTML.
  271. The optional argument 'display' can be set to 0 to suppress sending the
  272. traceback to the browser, and 'logdir' can be set to a directory to cause
  273. tracebacks to be written to files there."""
  274. sys.excepthook = Hook(display=display, logdir=logdir,
  275. context=context, format=format)