Analizar el traceback y armar un dict con la info amigable user-friendly
973889
def exception_info(current_filename=None, index=-1):
    ""
    # guardo el traceback original (por si hay una excepción):
    info = sys.exc_info() #         exc_type, exc_value, exc_traceback
    # importante: no usar unpacking porque puede causar memory leak
    if not current_filename:
        # genero un call stack para ver quien me llamó y limitar la traza: 
        # advertencia: esto es necesario ya que en py2exe no tengo __file__ 
        try:
            raise ZeroDivisionError
        except ZeroDivisionError:
            f = sys.exc_info()[2].tb_frame.f_back
        current_filename = os.path.normpath(os.path.abspath(f.f_code.co_filename))

    # extraer la última traza del archivo solicitado:
    # (útil para no alargar demasiado la traza con lineas de las librerías)
    ret = {'filename': "", 'lineno': 0, 'function_name': "", 'code': ""}
    try:
        for (filename, lineno, fn, text) in traceback.extract_tb(info[2]):
            if os.path.normpath(os.path.abspath(filename)) == current_filename:
                ret = {'filename': filename, 'lineno': lineno, 
                       'function_name': fn, 'code': text}
    except Exception, e:
        pass
    # obtengo el mensaje de excepcion tal cual lo formatea python:
    # (para evitar errores de encoding)
    try:
        ret['msg'] = traceback.format_exception_only(*info[0:2])[0]
    except: 
        ret['msg'] = '<no disponible>'
    # obtener el nombre de la excepcion (ej. "NameError")
    try:
        ret['name'] = info[0].__name__
    except:
        ret['name'] = 'Exception'
    # obtener la traza formateada como string:
    try:
        tb = traceback.format_exception(*info)
        ret['tb'] = ''.join(tb)
    except:
        ret['tb'] = ""
    return ret
340259
protected function trace()
    {
        foreach (\array_reverse($this->backtrace) as $stackFrame) {
            if ($this->isDebugCall($stackFrame)) {
                return $stackFrame;
            }
        }

        return \end($this->backtrace);
    }
935169
def get_trace(self):
        ''' '''

        tblist = traceback.extract_tb(sys.exc_info()[2])
        tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
                                           and ('pexpect/expect' not in item[0])]
        tblist = traceback.format_list(tblist)
        return ''.join(tblist)
1194921
private function getBacktraceUse()
    {
        $debugBacktrace = collect(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 30))->filter(function ($backtrace) {
            $backtraceClass = (isset($backtrace['class'])) ? $backtrace['class'] : null;

            return $backtraceClass === $this->listenClass;
        })->first();
        $checkBacktrace = null;
        $backtraceFile = (isset($debugBacktrace['file'])) ? $debugBacktrace['file'] : null;
        $backtraceFunction = (isset($debugBacktrace['function'])) ? $debugBacktrace['function'] : null;
        if (!is_null($debugBacktrace) && str_contains($backtraceFile, 'Illuminate/Database/Eloquent/SoftDeletingScope.php') && $backtraceFunction == 'update') {
            $checkBacktrace = [
                'object'   => $debugBacktrace['object'],
                'function' => $debugBacktrace['function'],
                'args'     => $debugBacktrace['args'][0],
            ];
        }

        return $checkBacktrace;
    }
923145
def trace_error(function_index=2):
    
    info = function_info(function_index)
    traces = traceback.format_stack(limit=10)
    for trace in traces:
        file_, line_number, line_text = trace.split(',', 2)
        if file_ == '  File "%s"' % info['file'] and\
                        line_number != 'line %s' % info['line_number']:
            return line_number.split()[-1], line_text.strip()
    return None, None
1282117
function(input) {

			var temp;

			// Si no hay parámetros

			if (!arguments.length) {

				// Construimos la URL con los atributos y la devolvemos como cadena de texto

				return Public.build(this._attributes, this.location);

			// Si el parámetro es `null`

			} else if (input === null) {

				// Vaciamos los atributos

				this._attributes = {};

			// Si el parámetro es una cadena de texto o un objecto

			} else if ((temp = typeof input) === 'string' || (input && temp === 'object')) {

				// Desmontamos la URL y guardamos su información en forma de objeto

				this._attributes = Public.unbuild(input, this.location);

			}

			return this;

		}
535984
def ConsultarCondicionesVenta(self, sep="||"):
        ""
        ret = self.client.consultarCondicionesVenta(
                        auth={
                            'token': self.Token, 'sign': self.Sign,
                            'cuit': self.Cuit, },
                            )['respuesta']
        self.__analizar_errores(ret)
        array = ret.get('condicionVenta', [])
        if sep is None:
            return dict([(it['codigo'], it['descripcion']) for it in array])
        else:
            return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
                    (it['codigo'], it['descripcion']) for it in array]
739149
def ConsultarPuntosVentas(self, sep="||"):
        ""
        ret = self.client.consultarPuntosVenta(
                        auth={
                            'token': self.Token, 'sign': self.Sign,
                            'cuit': self.Cuit, },
                            )['respuesta']
        self.__analizar_errores(ret)
        array = ret.get('puntoVenta', [])
        if sep is None:
            return dict([(it['codigo'], it['descripcion']) for it in array])
        else:
            return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
                    (it['codigo'], it['descripcion']) for it in array]
686404
def traceback_string():
    
    tb_string = None
    exc_type, exc_value, exc_traceback = traceback.sys.exc_info()
    if exc_type is not None:
        display_lines_list = [str(exc_value)] + traceback.format_tb(exc_traceback)
        tb_string = "\n".join(display_lines_list)
    return tb_string
1152711
public function getBacktrace( $trace )
    {
        $traces = [ ];

        $i = 1;

        foreach ( $trace as $t )
        {
            $traceString = '';

            if ( !isset( $t[ 'file' ] ) )
            {
                $t[ 'file' ] = 'unknown';
            }
            if ( !isset( $t[ 'line' ] ) )
            {
                $t[ 'line' ] = 0;
            }
            if ( !isset( $t[ 'function' ] ) )
            {
                $t[ 'function' ] = 'unknown';
            }

            $traceString .= '#' .
                $i . ' ' .
                $t[ 'file' ] . '(' .
                $t[ 'line' ] . '): ';

            if ( isset( $t[ 'object' ] ) && is_object( $t[ 'object' ] ) )
            {
                $traceString .= get_class( $t[ 'object' ] ) . '->';
            }

            $traceString .= $t[ 'function' ] . '()';

            $traces[ ] = $traceString;

            $i++;
        }

        return $traces;
    }
309245
public static function getStackTrace() {
    ob_start();
    debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
    $trace = ob_get_contents();
    ob_end_clean();

    // remove first item from backtrace as it's this function which is redundant.
    $trace = preg_replace('/^#0\s+'.__FUNCTION__."[^\n]*\n/", '', $trace, 1);

    return $trace;
  }
1289990
public static function dumpTrace()
    {
        $debug = debug_backtrace();
        $lines = '';
        $index = 0;

        for ($i = 0; $i < count($debug); $i++) {
            if ($i == 0) {
                continue;
            }
            $file = $debug[$i];
            if (!isset($file['file'])) {
                $file['file'] = 'eval';
            }
            if (!isset($file['line'])) {
                $file['line'] = null;
            }
            $line = "#{$index} {$file['file']}({$file['line']}): ";
            if (isset($file['class'])) {
                $line .= "{$file['class']}{$file['type']}";
            }
            $line .= "{$file['function']}(";
            if (isset($file['args']) && count($file['args'])) {
                foreach ($file['args'] as $arg) {
                    $line .= gettype($arg) . ', ';
                }
                $line = substr($line, 0, -2);
            }
            $line .= ')';
            $lines .= $line . "\n";
            $index++;
        } // for

        $lines .= "#{$index} {main}\n";

        if (ini_get('html_errors')) {
            echo nl2br(str_replace(' ', '&nbsp;', $lines));
        } else {
            echo $lines;
        }
    }
761427
public static function inspect()
	{
		$backtrace = debug_backtrace();

		// If being called from within, show the file above in the backtrack
		if (strpos($backtrace[0]['file'], 'core/classes/debug.php') !== false)
		{
			$callee = $backtrace[1];
			$label = \Inflector::humanize($backtrace[1]['function']);
		}
		else
		{
			$callee = $backtrace[0];
			$label = 'Debug';
		}

		$arguments = func_get_args();
		$total_arguments = count($arguments);

		$callee['file'] = \Fuel::clean_path($callee['file']);

		if ( ! static::$js_displayed)
		{
			echo <<<JS
<script type="text/javascript">function fuel_debug_toggle(a){if(document.getElementById){if(document.getElementById(a).style.display=="none"){document.getElementById(a).style.display="block"}else{document.getElementById(a).style.display="none"}}else{if(document.layers){if(document.id.display=="none"){document.id.display="block"}else{document.id.display="none"}}else{if(document.all.id.style.display=="none"){document.all.id.style.display="block"}else{document.all.id.style.display="none"}}}};</script>
JS;
			static::$js_displayed = true;
		}
		echo '<div class="fuelphp-inspect" style="font-size: 13px;background: #EEE !important; border:1px solid #666; color: #000 !important; padding:10px;">';
		echo '<h1 style="border-bottom: 1px solid #CCC; padding: 0 0 5px 0; margin: 0 0 5px 0; font: bold 120% sans-serif;">'.$callee['file'].' @ line: '.$callee['line'].'</h1>';
		echo '<pre style="overflow:auto;font-size:100%;">';
		$i = 0;
		foreach ($arguments as $argument)
		{
			echo '<strong>'.$label.' #'.(++$i).' of '.$total_arguments.'</strong>:<br />';
				echo static::format('...', $argument);
			echo '<br />';
		}

		echo "</pre>";
		echo "</div>";
	}
1186149
def showtraceback(self, *args, **kwargs):
        
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list)
1124740
def output_traceback(ex):
    """"""
    # Dump full traceback to console.
    output = "".join(traceback.format_exc()).strip()
    for line in output.split('\n'):
        logging.error(line)
    trace_obj = traceback.extract_tb(ex.__traceback__)[-1]
    trace = [basename(trace_obj[0]), trace_obj[1]]
    name = type(ex).__name__
    output = str(ex).replace('\n', ' ')
    msg = "%s in %s on line %s: %s" % (name, trace[0], trace[1], output)
    return (msg, output)
623893
public function loadCallLocationInfo()
    {
        $this->callFile = null;
        $this->callLine = null;

        $backtraceFlags = DEBUG_BACKTRACE_PROVIDE_OBJECT;
        if (version_compare(PHP_VERSION, '5.3.6', '>=')) {
            $backtraceFlags = DEBUG_BACKTRACE_IGNORE_ARGS;
        }

        $backtrace = debug_backtrace($backtraceFlags);

        $backtraceCount = count($backtrace);
        $idx = $backtraceCount - 1;
        $found = false;

        $container = $this->application->container;

        $helpers = array_merge(
            $container->getParameter('helpers'),
            $container->hasParameter('extra_helpers') ? $container->getParameter('extra_helpers') : array()
        );

        while ($idx > 0 && !$found) {
            $callable = isset($backtrace[$idx]['class']) ? $backtrace[$idx]['class'] . ':' . $backtrace[$idx]['function'] : $backtrace[$idx]['function'];

            if (in_array($callable, $helpers)) {
                $this->callFile = isset($backtrace[$idx]['file']) ? $backtrace[$idx]['file'] : null;
                $this->callLine = isset($backtrace[$idx]['line']) ? $backtrace[$idx]['line'] : null;

                if (!is_null($this->callLineFileCallback)) {
                    list($this->callFile, $this->callLine) = call_user_func_array($this->callLineFileCallback, array(
                        $this->callFile,
                        $this->callLine
                    ));
                }

                $xdebugLink = ini_get('xdebug.file_link_format');
                if (!empty($xdebugLink)) {
                    $this->xdebugLink = str_replace(array('%f', '%l'), array($this->callFile, $this->callLine), $xdebugLink);
                }

                return;
            }

            $idx--;
        }

    }
1210300
def format_traceback(extracted_tb,
                     exc_type,
                     exc_value,
                     cwd='',
                     term=None,
                     function_color=12,
                     dim_color=8,
                     editor='vi',
                     template=DEFAULT_EDITOR_SHORTCUT_TEMPLATE):
    
    def format_shortcut(editor,
                        path,
                        line_number,
                        function=None):
        """Return a pretty-printed editor shortcut."""
        return template.format(editor=editor,
                               line_number=line_number or 0,
                               path=path,
                               function=function or u'',
                               hash_if_function=u'  # ' if function else u'',
                               function_format=term.color(function_color),
                               # Underline is also nice and doesn't make us
                               # worry about appearance on different background
                               # colors.
                               normal=term.normal,
                               dim_format=term.color(dim_color) + term.bold,
                               line_number_max_width=line_number_max_width,
                               term=term)

    template += '\n'  # Newlines are awkward to express on the command line.
    extracted_tb = _unicode_decode_extracted_tb(extracted_tb)
    if not term:
        term = Terminal()

    if extracted_tb:
        # Shorten file paths:
        for i, (file, line_number, function, text) in enumerate(extracted_tb):
            extracted_tb[i] = human_path(src(file), cwd), line_number, function, text

        line_number_max_width = len(unicode(max(the_line for _, the_line, _, _ in extracted_tb)))

        # Stack frames:
        for i, (path, line_number, function, text) in enumerate(extracted_tb):
            text = (text and text.strip()) or u''

            yield (format_shortcut(editor, path, line_number, function) +
                   (u'    %s\n' % text))

    # Exception:
    if exc_type is SyntaxError:
        # Format a SyntaxError to look like our other traceback lines.
        # SyntaxErrors have a format different from other errors and include a
        # file path which looks out of place in our newly highlit, editor-
        # shortcutted world.
        if hasattr(exc_value, 'filename') and hasattr(exc_value, 'lineno'):
            exc_lines = [format_shortcut(editor, exc_value.filename, exc_value.lineno)]
            formatted_exception = format_exception_only(SyntaxError, exc_value)[1:]
        else:
            # The logcapture plugin may format exceptions as strings,
            # stripping them of the full filename and lineno
            exc_lines = []
            formatted_exception = format_exception_only(SyntaxError, exc_value)
            formatted_exception.append(u'(Try --nologcapture for a more detailed traceback)\n')
    else:
        exc_lines = []
        formatted_exception = format_exception_only(exc_type, exc_value)
    exc_lines.extend([_decode(f) for f in formatted_exception])
    yield u''.join(exc_lines)