Python inspect.trace() Examples

The following are 26 code examples of inspect.trace(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: contract.py    From pop with Apache License 2.0 6 votes vote down vote up
def get_arguments(self):
        '''
        Return a dictionary of all arguments that will be passed to the function and their
        values, including default arguments.
        '''
        if '__bound_signature__' not in self.cache:
            try:
                self.cache['__bound_signature__'] = self.signature.bind(*self.args, **self.kwargs)
            except TypeError as e:
                for frame in inspect.trace():
                    if frame.function == 'bind' and frame.filename.endswith(os.sep+'inspect.py'):
                        raise pop.exc.BindError(e)
                raise
            # Apply any default values from the signature
            self.cache['__bound_signature__'].apply_defaults()
        return self.cache['__bound_signature__'].arguments 
Example #2
Source File: views.py    From django-ai with GNU Lesser General Public License v3.0 6 votes vote down vote up
def run_action(self, action, action_object=None):
        try:
            if action_object:
                action_method = getattr(action_object, action['method'])
            else:
                action_method = getattr(self, action['method'])
            action_method(**action['kwargs'])
            messages.success(self.request,
                             "SUCCESS AT {}".format(action['str']))
        except Exception as e:
            msg = e.args[0]
            frm = inspect.trace()[-1]
            mod = inspect.getmodule(frm[0])
            modname = mod.__name__ if mod else frm[1]
            messages.error(self.request,
                           "ERROR WHILE {}: [{}] {}".format(
                               action['str'], modname, str(msg))) 
Example #3
Source File: _error_reporting.py    From pyquil with Apache License 2.0 6 votes vote down vote up
def pyquil_protect(
    func: Callable[..., Any], log_filename: str = "pyquil_error.log"
) -> Callable[..., Any]:
    """
    A decorator that sets up an error context, captures errors, and tears down the context.
    """

    def pyquil_protect_wrapper(*args: Any, **kwargs: Any) -> Any:
        global global_error_context

        old_error_context = global_error_context
        global_error_context = ErrorContext()
        global_error_context.filename = log_filename

        try:
            val = func(*args, **kwargs)
            global_error_context = old_error_context
            return val
        except Exception as e:
            assert global_error_context is not None
            global_error_context.dump_error(e, inspect.trace())
            global_error_context = old_error_context
            raise

    return pyquil_protect_wrapper 
Example #4
Source File: _error_reporting.py    From pyquil with Apache License 2.0 6 votes vote down vote up
def dump_error(self, exception: Exception, trace: List[inspect.FrameInfo]) -> None:
        warn_msg = """
>>> PYQUIL_PROTECT <<<
An uncaught exception was raised in a function wrapped in pyquil_protect.  We are writing out a
log file to "{}".

Along with a description of what you were doing when the error occurred, send this file to
Rigetti Computing support by email at support@rigetti.com for assistance.
>>> PYQUIL_PROTECT <<<
""".format(
            os.path.abspath(self.filename)
        )

        _log.warning(warn_msg)

        report = self.generate_report(exception, trace)

        # overwrite any existing log file
        fh = open(self.filename, "w")
        fh.write(json.dumps(report, default=json_serialization_helper))
        fh.close() 
Example #5
Source File: library.py    From knitter with GNU General Public License v3.0 6 votes vote down vote up
def exception_error():
    error_message = ""
    for i in range(len(inspect.trace())):
        error_line = """
File:      %s - [%s]
Function:  %s
Statement: %s
-------------------------------------------------------------------------------------------""" % \
                     (inspect.trace()[i][1], inspect.trace()[i][2], inspect.trace()[i][3], inspect.trace()[i][4])

    error_message = "%s%s" % (error_message, error_line)
    error_message = """Error!
%s
%s
======================================== Error Message ====================================%s

======================================== Error Message ======================================================""" % \
                    (sys.exc_info()[0], sys.exc_info()[1], error_message)

    return error_message 
Example #6
Source File: cli.py    From snscrape with GNU General Public License v3.0 5 votes vote down vote up
def _dump_stack_and_locals(trace, exc = None):
	with tempfile.NamedTemporaryFile('w', prefix = 'snscrape_locals_', delete = False) as fp:
		if exc is not None:
			fp.write('Exception:\n')
			fp.write(f'  {type(exc).__module__}.{type(exc).__name__}: {exc!s}\n')
			fp.write(f'  args: {exc.args!r}\n')
			fp.write('\n')

		fp.write('Stack:\n')
		for frameRecord in trace:
			fp.write(f'  File "{frameRecord.filename}", line {frameRecord.lineno}, in {frameRecord.function}\n')
			for line in frameRecord.code_context:
				fp.write(f'    {line.strip()}\n')
		fp.write('\n')

		for frameRecord in trace:
			module = inspect.getmodule(frameRecord[0])
			if not module.__name__.startswith('snscrape.') and module.__name__ != 'snscrape':
				continue
			locals_ = frameRecord[0].f_locals
			fp.write(f'Locals from file "{frameRecord.filename}", line {frameRecord.lineno}, in {frameRecord.function}:\n')
			for variableName in locals_:
				variable = locals_[variableName]
				varRepr = _repr(variableName, variable)
				fp.write(f'  {variableName} {type(variable)} = ')
				fp.write(varRepr.replace('\n', '\n  '))
				fp.write('\n')
			fp.write('\n')
			if 'self' in locals_ and hasattr(locals_['self'], '__dict__'):
				fp.write(f'Object dict:\n')
				fp.write(repr(locals_['self'].__dict__))
				fp.write('\n\n')
		name = fp.name
	return name 
Example #7
Source File: execute.py    From shoogle with GNU General Public License v3.0 5 votes vote down vote up
def run(options):
    """Run command execute."""
    service_id, resource_name, method_name = lib.pad_list(options.api_path.split(".", 2), 3)
    request_fd = (sys.stdin if options.json_request == "-" else open(options.json_request))
    method_options = lib.load_json(request_fd.read())
    try:
        response = do_request(service_id, resource_name, method_name, method_options, options)
        lib.output(lib.pretty_json(response))
    except TypeError as error:
        frm = inspect.trace()[-1]
        mod = inspect.getmodule(frm[0])
        if mod.__name__ == 'googleapiclient.discovery':
            config.logger.error("googleapiclient.discovery: {}".format(error))
        else:
            raise 
Example #8
Source File: inspect_fodder.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
Example #9
Source File: test_debug.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_template_exceptions(self):
        with self.assertLogs('django.request', 'ERROR'):
            try:
                self.client.get(reverse('template_exception'))
            except Exception:
                raising_loc = inspect.trace()[-1][-2][0].strip()
                self.assertNotEqual(
                    raising_loc.find("raise Exception('boom')"), -1,
                    "Failed to find 'raise Exception' in last frame of "
                    "traceback, instead found: %s" % raising_loc
                ) 
Example #10
Source File: test_debug.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_template_exceptions(self):
        with self.assertLogs('django.request', 'ERROR'):
            try:
                self.client.get(reverse('template_exception'))
            except Exception:
                raising_loc = inspect.trace()[-1][-2][0].strip()
                self.assertNotEqual(
                    raising_loc.find("raise Exception('boom')"), -1,
                    "Failed to find 'raise Exception' in last frame of "
                    "traceback, instead found: %s" % raising_loc
                ) 
Example #11
Source File: inspect_fodder.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
Example #12
Source File: notification.py    From senlin with Apache License 2.0 5 votes vote down vote up
def from_exception(cls, exc):
        if exc is None:
            return None
        trace = inspect.trace()[-1]
        module = inspect.getmodule(trace[0])
        module_name = module.__name__ if module else 'unknown'
        return cls(function=trace[3], module=module_name,
                   exception=exc.__class__.__name__,
                   message=str(exc)) 
Example #13
Source File: inspect_fodder.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
Example #14
Source File: inspect_fodder.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace() 
Example #15
Source File: exception.py    From watcher with Apache License 2.0 5 votes vote down vote up
def from_exception(cls, fault=None):
        fault = fault or sys.exc_info()[1]
        trace = inspect.trace()[-1]
        # TODO(gibi): apply strutils.mask_password on exception_message and
        # consider emitting the exception_message only if the safe flag is
        # true in the exception like in the REST API
        return cls(
            function_name=trace[3],
            module_name=inspect.getmodule(trace[0]).__name__,
            exception=fault.__class__.__name__,
            exception_message=str(fault)) 
Example #16
Source File: inspect_fodder.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
Example #17
Source File: cli.py    From snscrape with GNU General Public License v3.0 5 votes vote down vote up
def _dump_locals_on_exception():
	try:
		yield
	except Exception as e:
		trace = inspect.trace()
		if len(trace) >= 2:
			name = _dump_stack_and_locals(trace[1:], exc = e)
			logger.fatal(f'Dumped stack and locals to {name}')
		raise 
Example #18
Source File: run.py    From brownie with MIT License 5 votes vote down vote up
def main():
    args = docopt(__doc__)
    _update_argv_from_docopt(args)

    if project.check_for_project():
        active_project = project.load()
        active_project.load_config()
        print(f"{active_project._name} is the active project.")
    else:
        raise ProjectNotFound

    network.connect(CONFIG.argv["network"])

    path, _ = _get_path(args["<filename>"])
    path_str = path.absolute().as_posix()

    try:
        run(args["<filename>"], method_name=args["<function>"] or "main")
    except Exception as e:
        print(color.format_tb(e))

        if args["--interactive"]:
            frame = next(
                (i.frame for i in inspect.trace()[::-1] if Path(i.filename).as_posix() == path_str),
                None,
            )
            if frame is not None:
                globals_dict = {k: v for k, v in frame.f_globals.items() if not k.startswith("__")}

                shell = Console(active_project, {**globals_dict, **frame.f_locals})
                shell.interact(
                    banner="\nInteractive mode enabled. Use quit() to close.", exitmsg=""
                )
        sys.exit(1)

    if CONFIG.argv["gas"]:
        print("\n======= Gas profile =======")
        for line in _build_gas_profile_output():
            print(line) 
Example #19
Source File: exception.py    From masakari with Apache License 2.0 5 votes vote down vote up
def from_exc_and_traceback(cls, fault, traceback):
        trace = inspect.trace()[-1]
        # TODO(gibi): apply strutils.mask_password on exception_message and
        # consider emitting the exception_message only if the safe flag is
        # true in the exception like in the REST API
        module = inspect.getmodule(trace[0])
        module_name = module.__name__ if module else 'unknown'
        return cls(
            function_name=trace[3],
            module_name=module_name,
            exception=fault.__class__.__name__,
            exception_message=six.text_type(fault),
            traceback=traceback) 
Example #20
Source File: inspect_fodder.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
Example #21
Source File: inspect_fodder.py    From BinderFilter with MIT License 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
Example #22
Source File: _error_reporting.py    From pyquil with Apache License 2.0 5 votes vote down vote up
def generate_report(self, exception: Exception, trace: List[inspect.FrameInfo]) -> ErrorReport:
        """
        Handle an error generated in a routine decorated with the pyQuil error handler.

        :param exception: Exception object that generated this error.
        :param trace: inspect.trace object from the frame that caught the error.
        :return: ErrorReport object
        """
        stack_trace = [
            StacktraceFrame(
                name=item.function,
                filename=item.filename,
                line_number=item.lineno,
                locals={
                    k: serialize_object_for_logging(v) for (k, v) in item.frame.f_locals.items()
                },
            )
            for item in trace
        ]

        system_info = generate_system_info()

        report = ErrorReport(
            stack_trace=stack_trace,
            timestamp=datetime.utcnow(),
            exception=exception,
            system_info=system_info,
            call_log=flatten_log(self.log),
        )

        return report 
Example #23
Source File: inspect_fodder.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
Example #24
Source File: inspect_fodder.py    From oss-ftp with MIT License 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
Example #25
Source File: inspect_fodder.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace() 
Example #26
Source File: simpleplugin.py    From plugin.video.auvio with GNU General Public License v3.0 4 votes vote down vote up
def debug_exception(logger=None):
    """
    Diagnostic helper context manager

    It controls execution within its context and writes extended
    diagnostic info to the Kodi log if an unhandled exception
    happens within the context. The info includes the following items:

    - Module path.
    - Code fragment where the exception has happened.
    - Global variables.
    - Local variables.

    After logging the diagnostic info the exception is re-raised.

    Example::

        with debug_exception():
            # Some risky code
            raise RuntimeError('Fatal error!')

    :param logger: logger function which must accept a single argument
        which is a log message. By default it is :func:`xbmc.log`
        with ``ERROR`` level.
    """
    try:
        yield
    except:
        if logger is None:
            logger = lambda msg: xbmc.log(msg, xbmc.LOGERROR)
        logger('Unhandled exception detected!')
        logger('*** Start diagnostic info ***')
        frame_info = inspect.trace(5)[-1]
        logger('File: {0}'.format(frame_info[1]))
        context = ''
        for i, line in enumerate(frame_info[4], frame_info[2] - frame_info[5]):
            if i == frame_info[2]:
                context += '{0}:>{1}'.format(str(i).rjust(5), line)
            else:
                context += '{0}: {1}'.format(str(i).rjust(5), line)
        logger('Code context:\n' + context)
        logger('Global variables:\n' + _format_vars(frame_info[0].f_globals))
        logger('Local variables:\n' + _format_vars(frame_info[0].f_locals))
        logger('**** End diagnostic info ****')
        raise