Python inspect.getframeinfo() Examples

The following are 30 code examples of inspect.getframeinfo(). 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: install.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #2
Source File: install.py    From python-netsurv with MIT License 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #3
Source File: install.py    From jbox with MIT License 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #4
Source File: dependency_manager.py    From GelReportModels with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        filename = inspect.getframeinfo(inspect.currentframe()).filename
        path = os.path.dirname(os.path.abspath(filename))
        dependencies_json = "{}/../resources/builds.json".format(path)
        if not os.path.exists(dependencies_json):
            raise ValueError("Not found config file '{}'. Try running 'mvn initialize'".format(dependencies_json))
        builds = json.load(open(dependencies_json))["builds"]

        # prepares resource: version -> namespace -> python package
        self.builds = {}
        for build in builds:
            self.builds[build["version"]] = {}
            for package in build["packages"]:
                namespace = package["package"]
                _module = DependencyManager.get_python_module(package)
                self.builds[build["version"]][namespace] = _module 
Example #5
Source File: async_task.py    From asynq with Apache License 2.0 6 votes vote down vote up
def _traceback_line(self):
        frame = self._frame
        if frame is None and self._generator is not None:
            frame = debug.get_frame(self._generator)

        if frame is not None:
            frame_info = inspect.getframeinfo(frame)
            template = """File "%(file)s", line %(lineno)s, in %(funcname)s
    %(codeline)s"""
            return template % {
                "file": frame_info.filename,
                "lineno": frame_info.lineno,
                "funcname": frame_info.function,
                "codeline": "\n".join(frame_info.code_context).strip(),
            }
        else:
            return str(self) 
Example #6
Source File: install.py    From python-netsurv with MIT License 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #7
Source File: install.py    From pledgeservice with Apache License 2.0 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #8
Source File: install.py    From lambda-packs with MIT License 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #9
Source File: install.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #10
Source File: install.py    From lambda-chef-node-cleanup with Apache License 2.0 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #11
Source File: mock_callable.py    From TestSlide with MIT License 6 votes vote down vote up
def mock_async_callable(
    target,
    method,
    callable_returns_coroutine=False,
    allow_private=False,
    type_validation=True,
):
    caller_frame = inspect.currentframe().f_back
    # loading the context ends up reading files from disk and that might block
    # the event loop, so we don't do it.
    caller_frame_info = inspect.getframeinfo(caller_frame, context=0)
    return _MockAsyncCallableDSL(
        target,
        method,
        caller_frame_info,
        callable_returns_coroutine,
        allow_private,
        type_validation,
    ) 
Example #12
Source File: strict_mock.py    From TestSlide with MIT License 6 votes vote down vote up
def _get_caller(self, depth):
        # Doing inspect.stack will retrieve the whole stack, including context
        # and that is really slow, this only retrieves the minimum, and does
        # not read the file contents.
        caller_frame = self._get_caller_frame(depth)
        # loading the context ends up reading files from disk and that might block
        # the event loop, so we don't do it.
        frameinfo = inspect.getframeinfo(caller_frame, context=0)
        filename = frameinfo.filename
        lineno = frameinfo.lineno
        if self.TRIM_PATH_PREFIX:
            split = filename.split(self.TRIM_PATH_PREFIX)
            if len(split) == 2 and not split[0]:
                filename = split[1]
        if os.path.exists(filename):
            return "{}:{}".format(filename, lineno)
        else:
            return None 
Example #13
Source File: read_tweepy.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def launch_lsh_calc(self):
        # store tweets and kick off run_lsh

        tw_from = self.cursor
        tw_till = len(self.tweets)
        dui = ndb.Key(urlsafe = self.duik).get()
        dui = dui.extend_tweets(self.tweets[tw_from:tw_till])
        self.cursor = len(self.tweets)

        if not self.matrix:
            Matrix._initialize()
            MatrixRow._initialize()
            self.matrix = Matrix.create(filename = dui.filename(), source = 'tweets', file_key = self.duik)
            if self.matrix:
                dui = dui.set_ds_key(self.matrix.ds_key)
        if self.matrix:
            timestamp = datetime.datetime.utcnow().isoformat()
            deferred.defer(run_lsh, self.duik, self.tweets[tw_from:tw_till], self.matrix.ds_key, tw_from, timestamp)
        else:
            frameinfo = getframeinfo(currentframe())
            logging.error('file %s, line %s Matrix is missing', frameinfo.filename, frameinfo.lineno+1) 
Example #14
Source File: trace_logger.py    From tcex with Apache License 2.0 6 votes vote down vote up
def findCaller(
        self, stack_info=False, stack_level=1
    ):  # pylint: disable=arguments-differ,unused-argument
        """Find the caller for the current log event.

        Args:
            stack_info (bool, optional): Defaults to False.

        Returns:
            tuple: The caller stack information.
        """
        caller = None
        depth = 3
        while True:
            # search for the correct calling method
            caller = getframeinfo(stack()[depth][0])
            if caller.function != 'trace' or depth >= 6:
                break
            depth += 1

        return (caller.filename, caller.lineno, caller.function, None) 
Example #15
Source File: gctools.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _format(self, obj, descend=True):
        """Return a string representation of a single object."""
        if inspect.isframe(obj):
            filename, lineno, func, context, index = inspect.getframeinfo(obj)
            return "<frame of function '%s'>" % func

        if not descend:
            return self.peek(repr(obj))

        if isinstance(obj, dict):
            return '{' + ', '.join(['%s: %s' % (self._format(k, descend=False),
                                                self._format(v, descend=False))
                                    for k, v in obj.items()]) + '}'
        elif isinstance(obj, list):
            return '[' + ', '.join([self._format(item, descend=False)
                                    for item in obj]) + ']'
        elif isinstance(obj, tuple):
            return '(' + ', '.join([self._format(item, descend=False)
                                    for item in obj]) + ')'

        r = self.peek(repr(obj))
        if isinstance(obj, (str, int, float)):
            return r
        return '%s: %s' % (type(obj), r) 
Example #16
Source File: test_logging.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_log_error(self, logger):
        """
        ``log_error`` encodes module, function, and line number in the
        message_type, and passes other keyword arguments onto the message
        structure.
        """
        frame = getframeinfo(currentframe())
        log_error(key='VAL')
        line_no = frame.lineno + 1

        self.assertThat(
            logger.messages,
            AnyMatch(
                _dict_values_match(
                    message_type=ContainsAll(
                        [__name__, u'test_log_error', unicode(line_no)]),
                    key=Equals('VAL')
                )
            )
        ) 
Example #17
Source File: test_logging.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_log_info(self, logger):
        """
        ``log_info`` encodes module, function, and line number in the
        message_type, and passes other keyword arguments onto the message
        structure.
        """
        frame = getframeinfo(currentframe())
        log_info(key='VAL')
        line_no = frame.lineno + 1

        self.assertThat(
            logger.messages,
            AnyMatch(
                _dict_values_match(
                    message_type=ContainsAll(
                        [__name__, u'test_log_info', unicode(line_no)]),
                    key=Equals('VAL')
                )
            )
        ) 
Example #18
Source File: install.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #19
Source File: install.py    From pex with Apache License 2.0 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #20
Source File: install.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #21
Source File: install.py    From anpr with Creative Commons Attribution 4.0 International 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #22
Source File: install.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #23
Source File: install.py    From oss-ftp with MIT License 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #24
Source File: exceptions.py    From f5-openstack-agent with Apache License 2.0 6 votes vote down vote up
def __set_message(self, args, kargs):
        details = ', '.join(map(str, args))
        errno = kargs['errno'] if 'errno' in kargs and kargs['errno'] else \
            self.default_errno
        self.errno = errno
        message = kargs['message'] if 'message' in kargs and kargs['message'] \
            else self.default_msg
        exception = ''
        if 'frame' in kargs and kargs['frame']:
            frame = kargs['frame']
        else:
            my_frames = inspect.getouterframes(inspect.currentframe())[2]
            frame = inspect.getframeinfo(my_frames[0])
        if 'exception' in kargs and kargs['exception']:
            message = kargs['exception']
        elif details:
            exception = details
        self.frame = frame
        self.message = self.message_format % (errno, message, exception,
                                              frame.filename, frame.lineno) 
Example #25
Source File: op_graph.py    From ngraph-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, **kwargs):
        # TODO This is a good first cut for debugging info, but it would be nice to
        # TODO be able to reliably walk the stack back to user code rather than just
        # TODO back past this constructor
        super(DebugInfo, self).__init__(**kwargs)
        frame = None
        try:
            frame = inspect.currentframe()
            while frame.f_locals.get('self', None) is self:
                frame = frame.f_back
            while frame:
                filename, lineno, function, code_context, index = inspect.getframeinfo(
                    frame)
                if -1 == filename.find('ngraph/op_graph'):
                    break
                frame = frame.f_back

            self.filename = filename
            self.lineno = lineno
            self.code_context = code_context
        finally:
            del frame 
Example #26
Source File: install.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _called_from_setup(run_frame):
        """
        Attempt to detect whether run() was called from setup() or by another
        command.  If called by setup(), the parent caller will be the
        'run_command' method in 'distutils.dist', and *its* caller will be
        the 'run_commands' method.  If called any other way, the
        immediate caller *might* be 'run_command', but it won't have been
        called by 'run_commands'. Return True in that case or if a call stack
        is unavailable. Return False otherwise.
        """
        if run_frame is None:
            msg = "Call stack not available. bdist_* commands may fail."
            warnings.warn(msg)
            if platform.python_implementation() == 'IronPython':
                msg = "For best results, pass -X:Frames to enable call stack."
                warnings.warn(msg)
            return True
        res = inspect.getouterframes(run_frame)[2]
        caller, = res[:1]
        info = inspect.getframeinfo(caller)
        caller_module = caller.f_globals.get('__name__', '')
        return (
            caller_module == 'distutils.dist'
            and info.function == 'run_commands'
        ) 
Example #27
Source File: label.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        """
        Defines how a Label is printed out, e.g. Gx:0 or Gcnot:1:2
        """
        #caller = inspect.getframeinfo(inspect.currentframe().f_back)
        #ky = "%s:%s:%d" % (caller[2],os.path.basename(caller[0]),caller[1])
        #debug_record[ky] = debug_record.get(ky, 0) + 1
        s = str(self.name)
        if self.args:  # test for None and len == 0
            s += ";" + ";".join(map(str, self.args))
        if self.sslbls:  # test for None and len == 0
            s += ":" + ":".join(map(str, self.sslbls))
        if self.time != 0.0:
            s += ("!%f" % self.time).rstrip('0').rstrip('.')
        return s 
Example #28
Source File: util.py    From Attention-Gated-Networks with MIT License 5 votes vote down vote up
def varname(p):
    for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
        m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
        if m:
            return m.group(1) 
Example #29
Source File: util.py    From llvm-zorg with Apache License 2.0 5 votes vote down vote up
def _write_message(kind, message):
    # Get the file/line where this message was generated.
    f = inspect.currentframe()
    # Step out of _write_message, and then out of wrapper.
    f = f.f_back.f_back
    file,line,_,_,_ = inspect.getframeinfo(f)
    location = '%s:%d' % (os.path.basename(file), line)

    print >>sys.stderr, '%s: %s: %s' % (location, kind, message) 
Example #30
Source File: exception_trace.py    From clikit with MIT License 5 votes vote down vote up
def _format_traceback_frame(self, io, tb):  # type: (IO, ...) -> Tuple[Any]
        frame_info = inspect.getframeinfo(tb)
        filename = frame_info.filename
        lineno = frame_info.lineno
        function = frame_info.function
        line = frame_info.code_context[0]

        stripped_line = line.lstrip(" ")
        try:
            tree = ast.parse(stripped_line, mode="exec")
            formatted = self._format_tree(tree, stripped_line, io)
            formatted = (len(line) - len(stripped_line)) * " " + formatted
        except SyntaxError:
            formatted = line

        return (
            io.format("<c1>{}</c1>".format(filename)),
            "<fg=blue;options=bold>{}</>".format(lineno) if not PY2 else lineno,
            "<b>{}</b>".format(function),
            formatted,
        )