當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。