def format_exception(self):
        etype, evalue, etb = self.exception_info
        python_version = 'Python ' + sys.version.split(
        )[0] + ': ' + sys.executable
        date = time.ctime(time.time())
        html_page = HTML()
        frames = []
        records = inspect.getinnerframes(etb, self.no_of_tb_steps)
        for frame, file, lnum, func_name, lines, index in records:
            file_name = ''
            if file:
                file_name = os.path.abspath(file)
            args, varargs, varkw, locals = inspect.getargvalues(frame)
            function_args = inspect.formatargvalues(args, varargs, varkw,
                                                    locals)

            def reader(line_num=lnum):
                try:
                    return linecache.getline(file, line_num)
                finally:
                    line_num += 1

            vars = scanvars(reader, frame, locals)
            if index:
                i = lnum - index
                for line in lines:
                    if i == lnum: continue
                    i += 1
            frames.append({
                'file_name': file_name,
                'function_args': function_args,
                'locals': vars
            })
Exemplo n.º 2
0
def get_error_snapshot(depth=5):
    """Return a dict describing a given traceback (based on cgitb.text)."""

    etype, evalue, etb = sys.exc_info()
    if isinstance(etype, type):
        etype = etype.__name__

    data = {}
    data["timestamp"] = datetime.datetime.utcnow().isoformat()
    data["python_version"] = sys.version
    platform_keys = [
        "machine",
        "node",
        "platform",
        "processor",
        "python_branch",
        "python_build",
        "python_compiler",
        "python_implementation",
        "python_revision",
        "python_version",
        "python_version_tuple",
        "release",
        "system",
        "uname",
        "version",
    ]

    data["platform_info"] = {
        key: getattr(platform, key)()
        for key in platform_keys
    }
    data["os_environ"] = {key: str(value) for key, value in os.environ.items()}
    data["traceback"] = traceback.format_exc()
    data["exception_type"] = str(etype)
    data["exception_value"] = str(evalue)

    # Loopover the stack frames
    items = inspect.getinnerframes(etb, depth)
    del etb  # Prevent circular references that would cause memory leaks
    data["stackframes"] = stackframes = []

    for frame, file, lnum, func, lines, idx in items:
        file = file and os.path.abspath(file) or "?"
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        # Basic frame information
        f = {"file": file, "func": func, "lnum": lnum}
        f["code"] = lines
        # FIXME: disable this for now until we understand why this goes into infinite loop
        if False:
            line_vars = cgitb.scanvars(lambda: linecache.getline(file, lnum),
                                       frame, locals)
            # Dump local variables (referenced in current line only)
            f["vars"] = {
                key: repr(value)
                for key, value in locals.items() if not key.startswith("__")
            }
        stackframes.append(f)

    return data
Exemplo n.º 3
0
def frame_parser(frame_record):
    """
    Parse given frame and return formatted values.
    :param frame_record: frame
    :return: tuple (fname, call, code, objects, local_vars)
    """
    frame, fname, lnum, func, lines, index = frame_record
    fname = fname and os.path.abspath(fname) or '?'
    args, varargs, varkw, local_vars = inspect.getargvalues(frame)

    call = ''
    if func != '?':
        call = func + inspect.formatargvalues(
            args, varargs, varkw, local_vars,
            formatvalue=lambda value: '=' + pydoc.text.repr(value))

    highlight = {}

    def reader(lnum=[lnum]):
        highlight[lnum[0]] = 1
        try:
            return linecache.getline(fname, lnum[0])
        finally:
            lnum[0] += 1

    code = format_code(lines, lnum, index)

    objects = cgitb.scanvars(reader, frame, local_vars)

    return (fname, call, code, objects, local_vars)
Exemplo n.º 4
0
def frame_parser(frame_record):
    """
    Parse given frame and return formatted values.
    :param frame_record: frame
    :return: tuple (fname, call, code, objects, local_vars)
    """
    frame, fname, lnum, func, lines, index = frame_record
    fname = fname and os.path.abspath(fname) or '?'
    args, varargs, varkw, local_vars = inspect.getargvalues(frame)

    call = ''
    if func != '?':
        call = func + inspect.formatargvalues(
            args,
            varargs,
            varkw,
            local_vars,
            formatvalue=lambda value: '=' + pydoc.text.repr(value))

    highlight = {}

    def reader(lnum=[lnum]):
        highlight[lnum[0]] = 1
        try:
            return linecache.getline(fname, lnum[0])
        finally:
            lnum[0] += 1

    code = format_code(lines, lnum, index)

    objects = cgitb.scanvars(reader, frame, local_vars)

    return (fname, call, code, objects, local_vars)
Exemplo n.º 5
0
def get_error_snapshot(depth=5):
    """Return a dict describing a given traceback (based on cgitb.text)."""

    etype, evalue, etb = sys.exc_info()
    if isinstance(etype, type):
        etype = etype.__name__

    data = {}
    data['timestamp'] = datetime.datetime.utcnow().isoformat()
    data['python_version'] = sys.version
    platform_keys = [
        'machine', 'node', 'platform', 'processor', 'python_branch', 'python_build',
        'python_compiler', 'python_implementation', 'python_revision', 'python_version',
        'python_version_tuple', 'release', 'system', 'uname', 'version']
    data['platform_info'] = {key: getattr(platform, key)() for key in platform_keys}
    data['os_environ'] = {key: str(value) for key, value in os.environ.items()}
    data['traceback'] = traceback.format_exc()
    data['exception_type'] = str(etype)
    data['exception_value'] = str(evalue)
    # loopover the stack frames
    items = inspect.getinnerframes(etb, depth)
    del etb # Prevent circular references that would cause memory leaks
    data['stackframes'] = stackframes = []
    for frame, file, lnum, func, lines, index in items:
        file = file and os.path.abspath(file) or '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        # basic frame information
        f = {'file': file, 'func': func, 'lnum': lnum}
        f['code'] = lines
        line_vars = cgitb.scanvars(lambda: linecache.getline(file, lnum), frame, locals)
        # dump local variables (referenced in current line only)
        f['vars'] = {key: str(value) for key, value in locals.items() if not key.startswith('__')}
        stackframes.append(f)

    return data
Exemplo n.º 6
0
def get_error_snapshot(depth=5):
    """Return a dict describing a given traceback (based on cgitb.text)."""

    etype, evalue, etb = sys.exc_info()
    if isinstance(etype, type):
        etype = etype.__name__

    data = {}
    data['timestamp'] = datetime.datetime.utcnow().isoformat()
    data['python_version'] = sys.version
    platform_keys = [
        'machine', 'node', 'platform', 'processor', 'python_branch',
        'python_build', 'python_compiler', 'python_implementation',
        'python_revision', 'python_version', 'python_version_tuple', 'release',
        'system', 'uname', 'version'
    ]
    data['platform_info'] = {
        key: getattr(platform, key)()
        for key in platform_keys
    }
    data['os_environ'] = {key: str(value) for key, value in os.environ.items()}
    data['traceback'] = traceback.format_exc()
    data['exception_type'] = str(etype)
    data['exception_value'] = str(evalue)
    # Loopover the stack frames
    items = inspect.getinnerframes(etb, depth)
    del etb  # Prevent circular references that would cause memory leaks
    data['stackframes'] = stackframes = []
    for frame, file, lnum, func, lines, idx in items:
        file = file and os.path.abspath(file) or '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        # Basic frame information
        f = {'file': file, 'func': func, 'lnum': lnum}
        f['code'] = lines
        line_vars = cgitb.scanvars(lambda: linecache.getline(file, lnum),
                                   frame, locals)
        # Dump local variables (referenced in current line only)
        f['vars'] = {
            key: repr(value)
            for key, value in locals.items() if not key.startswith('__')
        }
        stackframes.append(f)

    return data
Exemplo n.º 7
0
def snapshot(info=None, context=5, code=None, environment=None):
    """Return a dict describing a given traceback (based on cgitb.text)."""
    import time
    import linecache
    import inspect
    import pydoc
    import cgitb

    # if no exception info given, get current:
    etype, evalue, etb = info or sys.exc_info()

    if isinstance(etype, ClassType):
        etype = etype.__name__

    # create a snapshot dict with some basic information
    s = {}
    s['pyver'] = 'Python ' + sys.version.split(
    )[0] + ': ' + sys.executable + ' (prefix: %s)' % sys.prefix
    s['date'] = time.ctime(time.time())

    # start to process frames
    records = inspect.getinnerframes(etb, context)
    del etb  # Prevent circular references that would cause memory leaks
    s['frames'] = []
    for frame, file, lnum, func, lines, index in records:
        file = file and os.path.abspath(file) or '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = inspect.formatargvalues(
                args,
                varargs,
                varkw,
                locals,
                formatvalue=lambda value: '=' + pydoc.text.repr(value))

        # basic frame information
        f = {
            'file': file,
            'func': func,
            'call': call,
            'lines': {},
            'lnum': lnum
        }

        highlight = {}

        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try:
                return linecache.getline(file, lnum[0])
            finally:
                lnum[0] += 1

        vars = cgitb.scanvars(reader, frame, locals)

        # if it is a view, replace with generated code
        if file.endswith('html'):
            lmin = lnum > context and (lnum - context) or 0
            lmax = lnum + context
            lines = code.split("\n")[lmin:lmax]
            index = min(context, lnum) - 1

        if index is not None:
            i = lnum - index
            for line in lines:
                f['lines'][i] = line.rstrip()
                i += 1

        # dump local variables (referenced in current line only)
        f['dump'] = {}
        for name, where, value in vars:
            if name in f['dump']:
                continue
            if value is not cgitb.__UNDEF__:
                if where == 'global':
                    name = 'global ' + name
                elif where != 'local':
                    name = where + name.split('.')[-1]
                f['dump'][name] = pydoc.text.repr(value)
            else:
                f['dump'][name] = 'undefined'

        s['frames'].append(f)

    # add exception type, value and attributes
    s['etype'] = str(etype)
    s['evalue'] = str(evalue)
    s['exception'] = {}
    if isinstance(evalue, BaseException):
        for name in dir(evalue):
            value = pydoc.text.repr(getattr(evalue, name))
            s['exception'][name] = value

    # add all local values (of last frame) to the snapshot
    s['locals'] = {}
    for name, value in locals.items():
        s['locals'][name] = pydoc.text.repr(value)

    # add web2py environment variables
    for k, v in environment.items():
        if k in ('request', 'response', 'session'):
            s[k] = XML(str(BEAUTIFY(v)))

    return s
Exemplo n.º 8
0
def get_snapshot(exception, context=10):
	"""
	Return a dict describing a given traceback (based on cgitb.text)
	"""

	etype, evalue, etb = sys.exc_info()
	if isinstance(etype, types.ClassType):
		etype = etype.__name__

	# creates a snapshot dict with some basic information

	s = {
		'pyver': 'Python {version:s}: {executable:s} (prefix: {prefix:s})'.format(
			version = sys.version.split()[0],
			executable = sys.executable,
			prefix = sys.prefix
		),
		'timestamp': cstr(datetime.datetime.now()),
		'traceback': traceback.format_exc(),
		'frames': [],
		'etype': cstr(etype),
		'evalue': cstr(evalue),
		'exception': {},
		'locals': {}
	}

	# start to process frames
	records = inspect.getinnerframes(etb, 5)

	for frame, file, lnum, func, lines, index in records:
		file = file and os.path.abspath(file) or '?'
		args, varargs, varkw, locals = inspect.getargvalues(frame)
		call = ''

		if func != '?':
			call = inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '={}'.format(pydoc.text.repr(value)))

		# basic frame information
		f = {'file': file, 'func': func, 'call': call, 'lines': {}, 'lnum': lnum}

		def reader(lnum=[lnum]):
			try:
				return linecache.getline(file, lnum[0])
			finally:
				lnum[0] += 1

		vars = cgitb.scanvars(reader, frame, locals)

		# if it is a view, replace with generated code
		# if file.endswith('html'):
		# 	lmin = lnum > context and (lnum - context) or 0
		# 	lmax = lnum + context
		# 	lines = code.split("\n")[lmin:lmax]
		# 	index = min(context, lnum) - 1

		if index is not None:
			i = lnum - index
			for line in lines:
				f['lines'][i] = line.rstrip()
				i += 1

		# dump local variable (referenced in current line only)
		f['dump'] = {}
		for name, where, value in vars:
			if name in f['dump']:
				continue
			if value is not cgitb.__UNDEF__:
				if where == 'global':
					name = 'global {name:s}'.format(name=name)
				elif where != 'local':
					name = where + ' ' + name.split('.')[-1]
				f['dump'][name] = pydoc.text.repr(value)
			else:
				f['dump'][name] = 'undefined'

		s['frames'].append(f)

	# add exception type, value and attributes
	if isinstance(evalue, BaseException):
		for name in dir(evalue):
			# prevent py26 DeprecationWarning
			if (name != 'messages' or sys.version_info < (2.6)) and not name.startswith('__'):
				value = pydoc.text.repr(getattr(evalue, name))

				# render multilingual string properly
				if type(value)==str and value.startswith(b"u'"):
					value = eval(value)

				s['exception'][name] = encode(value)

	# add all local values (of last frame) to the snapshot
	for name, value in locals.items():
		if type(value)==str and value.startswith(b"u'"):
			value = eval(value)

		s['locals'][name] = pydoc.text.repr(value)

	return s
Exemplo n.º 9
0
def html_render(einfo=None, context=5, request=None):
    """Copied from cgitb.html() and altered to suit my needs and preferences."""
    
    # If no info passed, grab it from the sys library
    if einfo == None:
        einfo = sys.exc_info()
    
    etype, evalue, etb = einfo
    if isinstance(etype, type):
        etype = etype.__name__
    
    indent = str(('&nbsp;' * 6))
    frames = []
    records = inspect.getinnerframes(etb, context)
    
    final_file, final_line = "", 0
    
    for frame, the_file, lnum, func, lines, index in records:
        if the_file:
            file_path = os.path.abspath(the_file)
            final_file = file_path
            link = '<a href="file://{}">{}</a>'.format(file_path, pydoc.html.escape(file_path))
        else:
            the_file = link = '?'
        
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = 'in <strong>' + func + '</strong>' + \
                inspect.formatargvalues(args, varargs, varkw, locals,
                    formatvalue=lambda value: '=' + pydoc.html.repr(value))
        
        highlight = {}
        
        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try: return linecache.getline(the_file, lnum[0])
            finally: lnum[0] += 1
            
        try:
            vars = cgitb.scanvars(reader, frame, locals)
        except Exception:
            raise
        
        rows = []
        if index is not None:
            i = lnum - index
            for line in lines:
                num = "<span style='font-size:0.8em;'>" + '&nbsp;' * (5-len(str(i))) + str(i) + '</span>&nbsp;'
                if i in highlight:
                    final_line = i
                    line = '=&gt;%s%s' % (num, pydoc.html.preformat(line))
                    rows.append('<div style="{}">{}</div>'.format(styles['highlighted_row'], line))
                else:
                    line = '&nbsp;&nbsp;%s%s' % (num, pydoc.html.preformat(line))
                    rows.append('<div style="%s">%s</div>' % (styles['grey_text'], line))
                i += 1

        done, dump = {}, []
        for name, where, value in vars:
            if name in done: continue
            done[name] = 1
            if value is not cgitb.__UNDEF__:
                if where in ('global', 'builtin'):
                    name = ('<em>%s</em> ' % where) + "<strong>%s</strong>" % name
                elif where == 'local':
                    name = "<strong>%s</strong>" % name
                else:
                    name = where + "<strong>" + name.split('.')[-1] + "</strong>"
                dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
            else:
                dump.append(name + ' <em>undefined</em>')

        rows.append('<div style="{};font-size:0.9em;">{}</div>'.format(styles['grey_text'], ', '.join(dump)))
        
        frames.append('''
        <div style="{styles[frame]}">
            {link} {call}
            {rows}
        </div>'''.format(
            styles = styles,
            link = link,
            call = call,
            rows = '\n'.join(rows)
        ))
        
        final_file, final_line
    
    exception = ['<br><strong>%s</strong>: %s' % (pydoc.html.escape(str(etype)),
                                pydoc.html.escape(str(evalue)))]
    for name in dir(evalue):
        if name[:1] == '_': continue
        value = pydoc.html.repr(getattr(evalue, name))
        exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
    
    path = "NO PATH"
    referrer = "No request"
    
    if request != None:
        referrer = request.referrer
    
    output = """
    <div class="panel panel-danger">
        <div class="panel-heading">
            <i class="fa fa-exclamation-triangle fa-fw"></i>
            Traceback
        </div>
        
        <div class="panel-body">
            <h2>{etype}</h2>
            <table class="table table-striped table-condensed">
                <tr>
                    <td style="text-align:right;">UUID:</td>
                    <td>{_instance_uuid}</td>
                </tr>
                <tr>
                    <td style="text-align:right;">Exception type:</td>
                    <td>{etype}</td>
                </tr>
                <tr>
                    <td style="text-align:right;">Exception value:</td>
                    <td><pre style="background-color:inherit;border-width:0;padding:0;margin:0;">{evalue}</pre></td>
                </tr>
                <tr>
                    <td style="text-align:right;">Exception location:</td>
                    <td>{location}</td>
                </tr>
                <tr>
                    <td style="text-align:right;">Referrer:</td>
                    <td>{referrer}</td>
                </tr>
                <!--
                <tr>
                    <td style="text-align:right;">Python executable:</td>
                    <td>{python_exe}</td>
                </tr>
                -->
                <tr>
                    <td style="text-align:right;">Python version:</td>
                    <td>{pyver}</td>
                </tr>
                <tr>
                    <td style="text-align:right;vertical-align: top;">Python path:</td>
                    <td>{pypath}</td>
                </tr>
                <tr>
                    <td style="text-align:right;">Server time:</td>
                    <td>{server_time}</td>
                </tr>
            </table>
            
    </div>""".format(
        styles      = styles,
        
        url         = path,
        location    = final_file + ", line %d" % final_line,
        etype       = pydoc.html.escape(str(etype)),
        referrer    = referrer,
        evalue      = pydoc.html.escape(str(evalue)),
        pyver       = sys.version.split()[0],
        python_exe  = sys.executable,
        pypath      = "<br>".join(sys.path),
        server_time = datetime.now().strftime("%A, %d of %b %Y %H:%M:%S %Z"),
        file_path   = path,
        _instance_uuid = _instance_uuid,
        
        # Takes file path and removes the root/system path from it
        short_file_path = path.replace(sys.path[0], ""),
    )
    
    cache['traceback'] = ''.join(traceback.format_exception(etype, evalue, etb))
    
    # return output + ''.join(frames) + ''.join(exception) + '''
    return output + ''.join(frames) + '''</div>


<!-- %s

%s
-->

''' % (traceback_info, pydoc.html.escape(
          ''.join(traceback.format_exception(etype, evalue, etb))))
Exemplo n.º 10
0
def format_tb(einfo):
    """Return a plain text document describing a given traceback."""

    etype, evalue, etb = einfo
    if type(etype) is types.ClassType:
        etype = etype.__name__

    frames = [ 'Traceback (most recent call last):' ]
    records = inspect.getinnerframes(etb, context=7)
    for (frame, file_, lnum, func, lines, index) in records:
        (args, varargs, varkw, locals_) = inspect.getargvalues(frame)
        sig = inspect.formatargvalues(args, varargs, varkw, locals_,
                                      formatvalue=lambda value: '=' + pydoc.text.repr(value))

        rows = ['  File %r, line %d, in %s%s' % (file_, lnum, func, sig) ]

        # To print just current line
        if index is not None:
            rows.append('    %s' % lines[index].strip())

#        # To print with context:
#        if index is not None:
#            i = lnum - index
#            for line in lines:
#                num = '%5d ' % i
#                rows.append(num+line.rstrip())
#                i += 1

        def reader(lnum=[lnum]): #pylint: disable=W0102 
            try:
                return linecache.getline(file_, lnum[0])
            finally:
                lnum[0] += 1

        printed = set()
        rows.append('  Current bindings:')
        for (name, where, value) in scanvars(reader, frame, locals_):
            if name in printed:
                continue
            printed.add(name)
            if value is not __UNDEF__:
                if where == 'global':
                    where = '(global)'
                elif where != 'local':
                    name = where + name.split('.')[-1]
                    where = '(local)'
                else:
                    where = ''
                rows.append('    %s = %s %s' % (name, pydoc.text.repr(value), where))
            else:
                rows.append(name + ' undefined')

        rows.append('')
        frames.extend(rows)

    exception = ['Exception: %s: %s' % (etype.__name__, evalue)]
    if isinstance(evalue, BaseException):

        # We may list deprecated attributes when iteracting, but obviously
        # we do not need any warnings about that.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
                        
            for name in dir(evalue):
                if name.startswith('__'):
                    continue
    
                value = pydoc.text.repr(getattr(evalue, name))
                exception.append('  %s = %s' % (name, value))

    return '%s\n%s' % ('\n'.join(frames), '\n'.join(exception))
Exemplo n.º 11
0
def html_render(einfo=None, context=5, headers=True):
    """Copied from cgitb.html() and altered to suit my needs and preferences"""
    
    # If no info passed, grab it from the sys library
    if einfo == None:
        einfo = sys.exc_info()
    
    etype, evalue, etb = einfo
    if isinstance(etype, type):
        etype = etype.__name__
    
    indent = str(('&nbsp;' * 6))
    frames = []
    records = inspect.getinnerframes(etb, context)
    
    final_file, final_line = "", 0
    
    for frame, the_file, lnum, func, lines, index in records:
        if the_file:
            file_path = os.path.abspath(the_file)
            final_file = file_path
            link = '<a href="file://{}">{}</a>'.format(file_path, pydoc.html.escape(file_path))
        else:
            the_file = link = '?'
        
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = 'in <strong>' + func + '</strong>' + \
                inspect.formatargvalues(args, varargs, varkw, locals,
                    formatvalue=lambda value: '=' + pydoc.html.repr(value))
        
        highlight = {}
        
        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try: return linecache.getline(the_file, lnum[0])
            finally: lnum[0] += 1
        vars = cgitb.scanvars(reader, frame, locals)
        
        rows = []
        if index is not None:
            i = lnum - index
            for line in lines:
                num = "<span style='font-size:0.8em;'>" + '&nbsp;' * (5-len(str(i))) + str(i) + '</span>&nbsp;'
                if i in highlight:
                    final_line = i
                    line = '=&gt;%s%s' % (num, pydoc.html.preformat(line))
                    rows.append('<div style="{}">{}</div>'.format(styles['highlighted_row'], line))
                else:
                    line = '&nbsp;&nbsp;%s%s' % (num, pydoc.html.preformat(line))
                    rows.append('<div style="%s">%s</div>' % (styles['grey_text'], line))
                i += 1

        done, dump = {}, []
        for name, where, value in vars:
            if name in done: continue
            done[name] = 1
            if value is not cgitb.__UNDEF__:
                if where in ('global', 'builtin'):
                    name = ('<em>%s</em> ' % where) + "<strong>%s</strong>" % name
                elif where == 'local':
                    name = "<strong>%s</strong>" % name
                else:
                    name = where + "<strong>" + name.split('.')[-1] + "</strong>"
                dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
            else:
                dump.append(name + ' <em>undefined</em>')

        rows.append('<div style="{};font-size:0.9em;">{}</div>'.format(styles['grey_text'], ', '.join(dump)))
        
        frames.append('''
        <div style="{styles[frame]}">
            {link} {call}
            {rows}
        </div>'''.format(
            styles = styles,
            link = link,
            call = call,
            rows = '\n'.join(rows)
        ))
        
        final_file, final_line
    
    exception = ['<br><strong>%s</strong>: %s' % (pydoc.html.escape(str(etype)),
                                pydoc.html.escape(str(evalue)))]
    for name in dir(evalue):
        if name[:1] == '_': continue
        value = pydoc.html.repr(getattr(evalue, name))
        exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
    
    mode = common_f.get_val("mode", pages.default_page)
    if mode in pages.page_dict:
        path = "/".join(pages.page_dict[mode][1::-1])
    else:
        path = "NO PATH"
    
    output = """
    <html>
        <body style='padding:0;margin:0;'>
    
    <div id="exception_container" style="{styles[body]}">
        <div id="exception_header" style="{styles[header]}">
            <span style="font-size:2em;">{etype} at {short_file_path}.py</span><br />
            
            <div style="padding: 10px 30px;">
                <table border="0" cellspacing="0" cellpadding="5">
                    <tr>
                        <td style="text-align:right; width:200px;">Request url:</td>
                        <td>{url}.py</td>
                    </tr>
                    <tr>
                        <td style="text-align:right;">Exception type:</td>
                        <td>{etype}</td>
                    </tr>
                    <tr>
                        <td style="text-align:right;">Exception value:</td>
                        <td>{evalue}</td>
                    </tr>
                    <tr>
                        <td style="text-align:right;">Exception location:</td>
                        <td>{location}</td>
                    </tr>
                    <tr>
                        <td style="text-align:right;">Python executable:</td>
                        <td>{python_exe}</td>
                    </tr>
                    <tr>
                        <td style="text-align:right;">Python version:</td>
                        <td>{pyver}</td>
                    </tr>
                    <tr>
                        <td style="text-align:right;vertical-align: top;">Python path:</td>
                        <td>{pypath}</td>
                    </tr>
                    <tr>
                        <td style="text-align:right;">Server time:</td>
                        <td>{server_time}</td>
                    </tr>
                </table>
            </div>
        </div>
    
    </div>""".format(
        styles      = styles,
        
        url         = path,
        location    = final_file + ", line %d" % final_line,
        etype       = pydoc.html.escape(str(etype)),
        evalue      = pydoc.html.escape(str(evalue)),
        pyver       = sys.version.split()[0],
        python_exe  = sys.executable,
        pypath      = "<br>".join(sys.path),
        server_time = datetime.datetime.now().strftime("%A, %d of %b %Y %H:%M:%S %Z"),
        file_path   = path,
        
        # Takes file path and removes the root/system path from it
        short_file_path = path.replace(sys.path[0], ""),
    )
    
    if headers:
        output = "Content-type: text/html; charset=utf-8\n" + output
    
    # return output + ''.join(frames) + ''.join(exception) + '''
    return output + ''.join(frames) + '''


<!-- 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
-->

</body>
</html>
''' % pydoc.html.escape(
          ''.join(traceback.format_exception(etype, evalue, etb)))
Exemplo n.º 12
0
 def update_event(self, inp=-1):
     self.set_output_val(
         0, cgitb.scanvars(self.input(0), self.input(1), self.input(2)))
Exemplo n.º 13
0
def snapshot(info=None, context=5, code=None, environment=None):
    """Return a dict describing a given traceback (based on cgitb.text)."""
    import os, types, time, traceback, linecache, inspect, pydoc, cgitb

    # if no exception info given, get current:
    etype, evalue, etb = info or sys.exc_info()

    if type(etype) is types.ClassType:
        etype = etype.__name__

    # create a snapshot dict with some basic information
    s = {}
    s["pyver"] = "Python " + sys.version.split()[0] + ": " + sys.executable
    s["date"] = time.ctime(time.time())

    # start to process frames
    records = inspect.getinnerframes(etb, context)
    s["frames"] = []
    for frame, file, lnum, func, lines, index in records:
        file = file and os.path.abspath(file) or "?"
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ""
        if func != "?":
            call = inspect.formatargvalues(
                args, varargs, varkw, locals, formatvalue=lambda value: "=" + pydoc.text.repr(value)
            )

        # basic frame information
        f = {"file": file, "func": func, "call": call, "lines": {}, "lnum": lnum}

        highlight = {}

        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try:
                return linecache.getline(file, lnum[0])
            finally:
                lnum[0] += 1

        vars = cgitb.scanvars(reader, frame, locals)

        # if it is a view, replace with generated code
        if file.endswith("html"):
            lmin = lnum > context and (lnum - context) or 0
            lmax = lnum + context
            lines = code.split("\n")[lmin:lmax]
            index = min(context, lnum) - 1

        if index is not None:
            i = lnum - index
            for line in lines:
                f["lines"][i] = line.rstrip()
                i += 1

        # dump local variables (referenced in current line only)
        f["dump"] = {}
        for name, where, value in vars:
            if name in f["dump"]:
                continue
            if value is not cgitb.__UNDEF__:
                if where == "global":
                    name = "global " + name
                elif where != "local":
                    name = where + name.split(".")[-1]
                f["dump"][name] = pydoc.text.repr(value)
            else:
                f["dump"][name] = "undefined"

        s["frames"].append(f)

    # add exception type, value and attributes
    s["etype"] = str(etype)
    s["evalue"] = str(evalue)
    s["exception"] = {}
    if isinstance(evalue, BaseException):
        for name in dir(evalue):
            # prevent py26 DeprecatedWarning:
            if name != "message" or sys.version_info < (2.6):
                value = pydoc.text.repr(getattr(evalue, name))
                s["exception"][name] = value

    # add all local values (of last frame) to the snapshot
    s["locals"] = {}
    for name, value in locals.items():
        s["locals"][name] = pydoc.text.repr(value)

    # add web2py environment variables
    for k, v in environment.items():
        if k in ("request", "response", "session"):
            s[k] = BEAUTIFY(v)

    return s
Exemplo n.º 14
0
def get_snapshot(exception, context=10):
    """
	Return a dict describing a given traceback (based on cgitb.text)
	"""

    etype, evalue, etb = sys.exc_info()
    if isinstance(etype, types.ClassType):
        etype = etype.__name__

    # creates a snapshot dict with some basic information

    s = {
        'pyver':
        'Python {version:s}: {executable:s} (prefix: {prefix:s})'.format(
            version=sys.version.split()[0],
            executable=sys.executable,
            prefix=sys.prefix),
        'timestamp':
        cstr(datetime.datetime.now()),
        'traceback':
        traceback.format_exc(),
        'frames': [],
        'etype':
        cstr(etype),
        'evalue':
        cstr( ` evalue `),
        'exception': {},
        'locals': {}
    }

    # start to process frames
    records = inspect.getinnerframes(etb, 5)

    for frame, file, lnum, func, lines, index in records:
        file = file and os.path.abspath(file) or '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''

        if func != '?':
            call = inspect.formatargvalues(
                args,
                varargs,
                varkw,
                locals,
                formatvalue=lambda value: '={}'.format(pydoc.text.repr(value)))

        # basic frame information
        f = {
            'file': file,
            'func': func,
            'call': call,
            'lines': {},
            'lnum': lnum
        }

        def reader(lnum=[lnum]):
            try:
                return linecache.getline(file, lnum[0])
            finally:
                lnum[0] += 1

        vars = cgitb.scanvars(reader, frame, locals)

        # if it is a view, replace with generated code
        # if file.endswith('html'):
        # 	lmin = lnum > context and (lnum - context) or 0
        # 	lmax = lnum + context
        # 	lines = code.split("\n")[lmin:lmax]
        # 	index = min(context, lnum) - 1

        if index is not None:
            i = lnum - index
            for line in lines:
                f['lines'][i] = line.rstrip()
                i += 1

        # dump local variable (referenced in current line only)
        f['dump'] = {}
        for name, where, value in vars:
            if name in f['dump']:
                continue
            if value is not cgitb.__UNDEF__:
                if where == 'global':
                    name = 'global {name:s}'.format(name=name)
                elif where != 'local':
                    name = where + ' ' + name.split('.')[-1]
                f['dump'][name] = pydoc.text.repr(value)
            else:
                f['dump'][name] = 'undefined'

        s['frames'].append(f)

    # add exception type, value and attributes
    if isinstance(evalue, BaseException):
        for name in dir(evalue):
            # prevent py26 DeprecationWarning
            if (name != 'messages' or sys.version_info <
                (2.6)) and not name.startswith('__'):
                value = pydoc.text.repr(getattr(evalue, name))

                # render multilingual string properly
                if type(value) == str and value.startswith(b"u'"):
                    value = eval(value)

                s['exception'][name] = encode(value)

    # add all local values (of last frame) to the snapshot
    for name, value in locals.items():
        if type(value) == str and value.startswith(b"u'"):
            value = eval(value)

        s['locals'][name] = pydoc.text.repr(value)

    return s
Exemplo n.º 15
0
def get_snapshot(exception, context=10):
	"""
	Return a dict describing a given traceback (based on cgitb.text)
	"""

	etype, evalue, etb = sys.exc_info()
	if isinstance(etype, six.class_types):
		etype = etype.__name__

	# creates a snapshot dict with some basic information

	s = {
		"pyver": "Python {version:s}: {executable:s} (prefix: {prefix:s})".format(
			version=sys.version.split()[0], executable=sys.executable, prefix=sys.prefix
		),
		"timestamp": cstr(datetime.datetime.now()),
		"traceback": traceback.format_exc(),
		"frames": [],
		"etype": cstr(etype),
		"evalue": cstr(repr(evalue)),
		"exception": {},
		"locals": {},
	}

	# start to process frames
	records = inspect.getinnerframes(etb, 5)

	for frame, file, lnum, func, lines, index in records:
		file = file and os.path.abspath(file) or "?"
		args, varargs, varkw, locals = inspect.getargvalues(frame)
		call = ""

		if func != "?":
			call = inspect.formatargvalues(
				args, varargs, varkw, locals, formatvalue=lambda value: "={}".format(pydoc.text.repr(value))
			)

		# basic frame information
		f = {"file": file, "func": func, "call": call, "lines": {}, "lnum": lnum}

		def reader(lnum=[lnum]):
			try:
				return linecache.getline(file, lnum[0])
			finally:
				lnum[0] += 1

		vars = cgitb.scanvars(reader, frame, locals)

		# if it is a view, replace with generated code
		# if file.endswith('html'):
		# 	lmin = lnum > context and (lnum - context) or 0
		# 	lmax = lnum + context
		# 	lines = code.split("\n")[lmin:lmax]
		# 	index = min(context, lnum) - 1

		if index is not None:
			i = lnum - index
			for line in lines:
				f["lines"][i] = line.rstrip()
				i += 1

		# dump local variable (referenced in current line only)
		f["dump"] = {}
		for name, where, value in vars:
			if name in f["dump"]:
				continue
			if value is not cgitb.__UNDEF__:
				if where == "global":
					name = "global {name:s}".format(name=name)
				elif where != "local":
					name = where + " " + name.split(".")[-1]
				f["dump"][name] = pydoc.text.repr(value)
			else:
				f["dump"][name] = "undefined"

		s["frames"].append(f)

	# add exception type, value and attributes
	if isinstance(evalue, BaseException):
		for name in dir(evalue):
			if name != "messages" and not name.startswith("__"):
				value = pydoc.text.repr(getattr(evalue, name))
				s["exception"][name] = encode(value)

	# add all local values (of last frame) to the snapshot
	for name, value in locals.items():
		s["locals"][name] = value if isinstance(value, six.text_type) else pydoc.text.repr(value)

	return s
Exemplo n.º 16
0
def snapshot(info=None, context=5, code=None, environment=None):
    """Return a dict describing a given traceback (based on cgitb.text)."""
    import time
    import linecache
    import inspect
    import pydoc
    import cgitb

    # if no exception info given, get current:
    etype, evalue, etb = info or sys.exc_info()

    if isinstance(etype, types.ClassType):
        etype = etype.__name__

    # create a snapshot dict with some basic information
    s = {}
    s['pyver'] = 'Python ' + sys.version.split()[0] + ': ' + sys.executable + ' (prefix: %s)' % sys.prefix
    s['date'] = time.ctime(time.time())

    # start to process frames
    records = inspect.getinnerframes(etb, context)
    s['frames'] = []
    for frame, file, lnum, func, lines, index in records:
        file = file and os.path.abspath(file) or '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = inspect.formatargvalues(args, varargs, varkw, locals,
                                           formatvalue=lambda value: '=' + pydoc.text.repr(value))

        # basic frame information
        f = {'file': file, 'func': func, 'call': call, 'lines': {},
             'lnum': lnum}

        highlight = {}

        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try:
                return linecache.getline(file, lnum[0])
            finally:
                lnum[0] += 1
        vars = cgitb.scanvars(reader, frame, locals)

        # if it is a view, replace with generated code
        if file.endswith('html'):
            lmin = lnum > context and (lnum - context) or 0
            lmax = lnum + context
            lines = code.split("\n")[lmin:lmax]
            index = min(context, lnum) - 1

        if index is not None:
            i = lnum - index
            for line in lines:
                f['lines'][i] = line.rstrip()
                i += 1

        # dump local variables (referenced in current line only)
        f['dump'] = {}
        for name, where, value in vars:
            if name in f['dump']:
                continue
            if value is not cgitb.__UNDEF__:
                if where == 'global':
                    name = 'global ' + name
                elif where != 'local':
                    name = where + name.split('.')[-1]
                f['dump'][name] = pydoc.text.repr(value)
            else:
                f['dump'][name] = 'undefined'

        s['frames'].append(f)

    # add exception type, value and attributes
    s['etype'] = str(etype)
    s['evalue'] = str(evalue)
    s['exception'] = {}
    if isinstance(evalue, BaseException):
        for name in dir(evalue):
            # prevent py26 DeprecatedWarning:
            if name != 'message' or sys.version_info < (2.6):
                value = pydoc.text.repr(getattr(evalue, name))
                s['exception'][name] = value

    # add all local values (of last frame) to the snapshot
    s['locals'] = {}
    for name, value in locals.items():
        s['locals'][name] = pydoc.text.repr(value)

    # add web2py environment variables
    for k, v in environment.items():
        if k in ('request', 'response', 'session'):
            s[k] = XML(str(BEAUTIFY(v)))

    return s
Exemplo n.º 17
0
try:
    print(foo(1, 0))
except:
    et, ev, tb = sys.exc_info()
    #print(" ".join(traceback.format_exception(et,ev,tb)))
    frame_records = inspect.getinnerframes(tb)
    #print("\n","frame_records:",frame_records)
    frame, fname, lnum, func, lines, index = frame_records[1]
    args, varargs, varkw, local_vars = inspect.getargvalues(frame)

    #print("\n","args,varargs, varkw, local_vars:",args,varargs, varkw, local_vars)
    #print("\n","lines:",lines)
    def reader():
        return lines[index]

    objects = cgitb.scanvars(reader, frame, local_vars)
    #print("\n","Objects:",objects)

# Use case of traceback:
# hyperlink (link that takes us to place in code where error occured)
# UI apps (app must run event if exception occurs) -- use traceback to silently log exception somewhere
# Interactive debugging -> inspect every state of program
# PEP 3134, Chain exceptions
# https://pypi.org/project/ptb/
'''
try:
    do_stuff()
except Exception:
    print(traceback.format_exc())
   '''
#------------------------------------------------------------------