当前位置: 首页>>代码示例>>Python>>正文


Python inspect.trace方法代码示例

本文整理汇总了Python中inspect.trace方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.trace方法的具体用法?Python inspect.trace怎么用?Python inspect.trace使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inspect的用法示例。


在下文中一共展示了inspect.trace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: exception_error

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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 
开发者ID:hw712,项目名称:knitter,代码行数:22,代码来源:library.py

示例2: dump_error

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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() 
开发者ID:rigetti,项目名称:pyquil,代码行数:23,代码来源:_error_reporting.py

示例3: pyquil_protect

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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 
开发者ID:rigetti,项目名称:pyquil,代码行数:27,代码来源:_error_reporting.py

示例4: get_arguments

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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 
开发者ID:saltstack,项目名称:pop,代码行数:18,代码来源:contract.py

示例5: run_action

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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))) 
开发者ID:math-a3k,项目名称:django-ai,代码行数:19,代码来源:views.py

示例6: main

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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) 
开发者ID:eth-brownie,项目名称:brownie,代码行数:41,代码来源:run.py

示例7: run

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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 
开发者ID:tokland,项目名称:shoogle,代码行数:17,代码来源:execute.py

示例8: argue

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace()

# line 48 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:10,代码来源:inspect_fodder.py

示例9: argue

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
def argue(self, a, b, c):
        try:
            spam(a, b, c)
        except:
            self.ex = sys.exc_info()
            self.tr = inspect.trace() 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:8,代码来源:inspect_fodder.py

示例10: generate_report

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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 
开发者ID:rigetti,项目名称:pyquil,代码行数:33,代码来源:_error_reporting.py

示例11: from_exc_and_traceback

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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) 
开发者ID:openstack,项目名称:masakari,代码行数:15,代码来源:exception.py

示例12: _dump_locals_on_exception

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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 
开发者ID:JustAnotherArchivist,项目名称:snscrape,代码行数:11,代码来源:cli.py

示例13: _dump_stack_and_locals

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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 
开发者ID:JustAnotherArchivist,项目名称:snscrape,代码行数:36,代码来源:cli.py

示例14: from_exception

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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)) 
开发者ID:openstack,项目名称:watcher,代码行数:13,代码来源:exception.py

示例15: from_exception

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import trace [as 别名]
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)) 
开发者ID:openstack,项目名称:senlin,代码行数:11,代码来源:notification.py


注:本文中的inspect.trace方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。