- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathcgitb.py
319 lines (273 loc) · 11.7 KB
/
cgitb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
"""More comprehensive traceback formatting for Python scripts.
To enable this module, do:
import cgitb; cgitb.enable()
at the top of your script. The optional arguments to enable() are:
display - if true, tracebacks are displayed in the web browser
logdir - if set, tracebacks are written to files in this directory
context - number of lines of source code to show for each stack frame
format - 'text' or 'html' controls the output format
By default, tracebacks are displayed but not saved, the context is 5 lines
and the output format is 'html' (for backwards compatibility with the
original use of this module)
Alternatively, if you have caught an exception and want cgitb to display it
for you, call cgitb.handler(). The optional argument to handler() is a
3-item tuple (etype, evalue, etb) just like the value of sys.exc_info().
The default handler displays output as HTML.
"""
importinspect
importkeyword
importlinecache
importos
importpydoc
importsys
importtempfile
importtime
importtokenize
importtraceback
defreset():
"""Return a string that resets the CGI and browser to a known state."""
return'''<!--: spam
Content-Type: text/html
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
</font> </font> </font> </script> </object> </blockquote> </pre>
</table> </table> </table> </table> </table> </font> </font> </font>'''
__UNDEF__= [] # a special sentinel object
defsmall(text):
iftext:
return'<small>'+text+'</small>'
else:
return''
defstrong(text):
iftext:
return'<strong>'+text+'</strong>'
else:
return''
defgrey(text):
iftext:
return'<font color="#909090">'+text+'</font>'
else:
return''
deflookup(name, frame, locals):
"""Find the value for a given name in the given environment."""
ifnameinlocals:
return'local', locals[name]
ifnameinframe.f_globals:
return'global', frame.f_globals[name]
if'__builtins__'inframe.f_globals:
builtins=frame.f_globals['__builtins__']
iftype(builtins) istype({}):
ifnameinbuiltins:
return'builtin', builtins[name]
else:
ifhasattr(builtins, name):
return'builtin', getattr(builtins, name)
returnNone, __UNDEF__
defscanvars(reader, frame, locals):
"""Scan one logical line of Python and look up values of variables used."""
vars, lasttoken, parent, prefix, value= [], None, None, '', __UNDEF__
forttype, token, start, end, lineintokenize.generate_tokens(reader):
ifttype==tokenize.NEWLINE: break
ifttype==tokenize.NAMEandtokennotinkeyword.kwlist:
iflasttoken=='.':
ifparentisnot__UNDEF__:
value=getattr(parent, token, __UNDEF__)
vars.append((prefix+token, prefix, value))
else:
where, value=lookup(token, frame, locals)
vars.append((token, where, value))
eliftoken=='.':
prefix+=lasttoken+'.'
parent=value
else:
parent, prefix=None, ''
lasttoken=token
returnvars
defhtml(einfo, context=5):
"""Return a nice HTML document describing a given traceback."""
etype, evalue, etb=einfo
ifisinstance(etype, type):
etype=etype.__name__
pyver='Python '+sys.version.split()[0] +': '+sys.executable
date=time.ctime(time.time())
head='<body bgcolor="#f0f0f8">'+pydoc.html.heading(
'<big><big>%s</big></big>'%
strong(pydoc.html.escape(str(etype))),
'#ffffff', '#6622aa', pyver+'<br>'+date) +'''
<p>A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.</p>'''
indent='<tt>'+small(' '*5) +' </tt>'
frames= []
records=inspect.getinnerframes(etb, context)
forframe, file, lnum, func, lines, indexinrecords:
iffile:
file=os.path.abspath(file)
link='<a href="file://%s">%s</a>'% (file, pydoc.html.escape(file))
else:
file=link='?'
args, varargs, varkw, locals=inspect.getargvalues(frame)
call=''
iffunc!='?':
call='in '+strong(pydoc.html.escape(func)) + \
inspect.formatargvalues(args, varargs, varkw, locals,
formatvalue=lambdavalue: '='+pydoc.html.repr(value))
highlight= {}
defreader(lnum=[lnum]):
highlight[lnum[0]] =1
try: returnlinecache.getline(file, lnum[0])
finally: lnum[0] +=1
vars=scanvars(reader, frame, locals)
rows= ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>'%
('<big> </big>', link, call)]
ifindexisnotNone:
i=lnum-index
forlineinlines:
num=small(' '* (5-len(str(i))) +str(i)) +' '
ifiinhighlight:
line='<tt>=>%s%s</tt>'% (num, pydoc.html.preformat(line))
rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>'%line)
else:
line='<tt> %s%s</tt>'% (num, pydoc.html.preformat(line))
rows.append('<tr><td>%s</td></tr>'%grey(line))
i+=1
done, dump= {}, []
forname, where, valueinvars:
ifnameindone: continue
done[name] =1
ifvalueisnot__UNDEF__:
ifwherein ('global', 'builtin'):
name= ('<em>%s</em> '%where) +strong(name)
elifwhere=='local':
name=strong(name)
else:
name=where+strong(name.split('.')[-1])
dump.append('%s = %s'% (name, pydoc.html.repr(value)))
else:
dump.append(name+' <em>undefined</em>')
rows.append('<tr><td>%s</td></tr>'%small(grey(', '.join(dump))))
frames.append('''
<table width="100%%" cellspacing=0 cellpadding=0 border=0>
%s</table>'''%'\n'.join(rows))
exception= ['<p>%s: %s'% (strong(pydoc.html.escape(str(etype))),
pydoc.html.escape(str(evalue)))]
fornameindir(evalue):
ifname[:1] =='_': continue
value=pydoc.html.repr(getattr(evalue, name))
exception.append('\n<br>%s%s =\n%s'% (indent, name, value))
returnhead+''.join(frames) +''.join(exception) +'''
<!-- The above is a description of an error in a Python program, formatted
for a Web browser because the 'cgitb' module was enabled. In case you
are not reading this in a Web browser, here is the original traceback:
%s
-->
'''%pydoc.html.escape(
''.join(traceback.format_exception(etype, evalue, etb)))
deftext(einfo, context=5):
"""Return a plain text document describing a given traceback."""
etype, evalue, etb=einfo
ifisinstance(etype, type):
etype=etype.__name__
pyver='Python '+sys.version.split()[0] +': '+sys.executable
date=time.ctime(time.time())
head="%s\n%s\n%s\n"% (str(etype), pyver, date) +'''
A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.
'''
frames= []
records=inspect.getinnerframes(etb, context)
forframe, file, lnum, func, lines, indexinrecords:
file=fileandos.path.abspath(file) or'?'
args, varargs, varkw, locals=inspect.getargvalues(frame)
call=''
iffunc!='?':
call='in '+func+ \
inspect.formatargvalues(args, varargs, varkw, locals,
formatvalue=lambdavalue: '='+pydoc.text.repr(value))
highlight= {}
defreader(lnum=[lnum]):
highlight[lnum[0]] =1
try: returnlinecache.getline(file, lnum[0])
finally: lnum[0] +=1
vars=scanvars(reader, frame, locals)
rows= [' %s %s'% (file, call)]
ifindexisnotNone:
i=lnum-index
forlineinlines:
num='%5d '%i
rows.append(num+line.rstrip())
i+=1
done, dump= {}, []
forname, where, valueinvars:
ifnameindone: continue
done[name] =1
ifvalueisnot__UNDEF__:
ifwhere=='global': name='global '+name
elifwhere!='local': name=where+name.split('.')[-1]
dump.append('%s = %s'% (name, pydoc.text.repr(value)))
else:
dump.append(name+' undefined')
rows.append('\n'.join(dump))
frames.append('\n%s\n'%'\n'.join(rows))
exception= ['%s: %s'% (str(etype), str(evalue))]
fornameindir(evalue):
value=pydoc.text.repr(getattr(evalue, name))
exception.append('\n%s%s = %s'% (" "*4, name, value))
returnhead+''.join(frames) +''.join(exception) +'''
The above is a description of an error in a Python program. Here is
the original traceback:
%s
'''%''.join(traceback.format_exception(etype, evalue, etb))
classHook:
"""A hook to replace sys.excepthook that shows tracebacks in HTML."""
def__init__(self, display=1, logdir=None, context=5, file=None,
format="html"):
self.display=display# send tracebacks to browser if true
self.logdir=logdir# log tracebacks to files if not None
self.context=context# number of source code lines per frame
self.file=fileorsys.stdout# place to send the output
self.format=format
def__call__(self, etype, evalue, etb):
self.handle((etype, evalue, etb))
defhandle(self, info=None):
info=infoorsys.exc_info()
ifself.format=="html":
self.file.write(reset())
formatter= (self.format=="html") andhtmlortext
plain=False
try:
doc=formatter(info, self.context)
except: # just in case something goes wrong
doc=''.join(traceback.format_exception(*info))
plain=True
ifself.display:
ifplain:
doc=pydoc.html.escape(doc)
self.file.write('<pre>'+doc+'</pre>\n')
else:
self.file.write(doc+'\n')
else:
self.file.write('<p>A problem occurred in a Python script.\n')
ifself.logdirisnotNone:
suffix= ['.txt', '.html'][self.format=="html"]
(fd, path) =tempfile.mkstemp(suffix=suffix, dir=self.logdir)
try:
withos.fdopen(fd, 'w') asfile:
file.write(doc)
msg='%s contains the description of this error.'%path
except:
msg='Tried to save traceback to %s, but failed.'%path
ifself.format=='html':
self.file.write('<p>%s</p>\n'%msg)
else:
self.file.write(msg+'\n')
try:
self.file.flush()
except: pass
handler=Hook().handle
defenable(display=1, logdir=None, context=5, format="html"):
"""Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the
traceback to the browser, and 'logdir' can be set to a directory to cause
tracebacks to be written to files there."""
sys.excepthook=Hook(display=display, logdir=logdir,
context=context, format=format)