Python sys.getprofile() Examples

The following are code examples for showing how to use sys.getprofile(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: beacon-py   Author: deepsourcelabs   File: tracer.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _trace(self, frame, event, arg):
        """The trace function which is passed to `sys.setprofile`.

        We only track the `call` event here, since we only need to
        identify the usage of code, and not actually do any profiling. For all
        other events, we exit without doing anything.
        """

        filename, lineno = frame.f_code.co_filename, frame.f_lineno

        if (self.stopped and sys.getprofile() == self._trace):
            sys.setprofile(None)
            return None

        if event == 'call' and self._should_capture(filename):
            self._capture(filename, lineno)

        return self._trace 
Example 2
Project: pytypes   Author: Stewori   File: type_util.py    Apache License 2.0 6 votes vote down vote up
def restore_profiler():
    """If a typechecking profiler is active, e.g. created by
    pytypes.set_global_typechecked_profiler(), such a profiler
    must be restored whenever a TypeCheckError is caught.
    The call must stem from the thread that raised the error.
    Otherwise the typechecking profiler is implicitly disabled.
    Alternatively one can turn pytypes into warning mode. In that
    mode no calls to this function are required (unless one uses
    filterwarnings("error") or likewise).
    """
    idn = threading.current_thread().ident
    if not sys.getprofile() is None:
        warn("restore_profiler: Current profile is not None!")
    if not idn in _saved_profilers:
        warn("restore_profiler: No saved profiler for calling thread!")
    else:
        sys.setprofile(_saved_profilers[idn])
        del _saved_profilers[idn] 
Example 3
Project: pytypes   Author: Stewori   File: type_util.py    Apache License 2.0 6 votes vote down vote up
def start(self):
        if self._active:
            raise RuntimeError('type checker already running')
        elif self._pending:
            raise RuntimeError('type checker already starting up')
        self._pending = True
        # Install this instance as the current profiler
        self._previous_profiler = sys.getprofile()
        self._set_caller_level_shift(0)
        sys.setprofile(self)

        # If requested, set this instance as the default profiler for all future threads
        # (does not affect existing threads)
        if self.all_threads:
            self._previous_thread_profiler = threading._profile_hook
            threading.setprofile(self)
        self._active, self._pending = True, False 
Example 4
Project: pytypes   Author: Stewori   File: type_util.py    Apache License 2.0 6 votes vote down vote up
def stop(self):
        if self._active and not self._pending:
            self._pending = True
            if sys.getprofile() is self:
                sys.setprofile(self._previous_profiler)
                if not self._previous_profiler is None and \
                        isinstance(self._previous_profiler, TypeAgent):
                    self._previous_profiler._set_caller_level_shift(0)
            else:
                if sys.getprofile() is not None or not self._cleared:
                    warn('the system profiling hook has changed unexpectedly')
            if self.all_threads:
                if threading._profile_hook is self:
                    threading.setprofile(self._previous_thread_profiler)
                else:  # pragma: no cover
                    warn('the threading profiling hook has changed unexpectedly')
            self._active, self._pending = False, False 
Example 5
Project: pyblish-win   Author: pyblish   File: test_sys_setprofile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_empty(self):
        self.assertIsNone(sys.getprofile()) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_sys_setprofile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn) 
Example 7
Project: NiujiaoDebugger   Author: MrSrc   File: test_sys_setprofile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_empty(self):
        self.assertIsNone(sys.getprofile()) 
Example 8
Project: NiujiaoDebugger   Author: MrSrc   File: test_sys_setprofile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn) 
Example 9
Project: beacon-py   Author: deepsourcelabs   File: test_tracer.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_tracer_install_on_start(tracer):
    # initialize and start the tracer, and verify that it installs a
    # profiler
    tracer.start()

    assert sys.getprofile() == tracer._trace
    assert str(sys.getprofile()) == str(tracer._trace) 
Example 10
Project: beacon-py   Author: deepsourcelabs   File: test_tracer.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_tracer_should_remove_on_stop(tracer):
    # first start the tracer
    tracer.start()

    # then stop the tracer and assert that the profiler has been removed
    tracer.stop()
    assert sys.getprofile() is None 
Example 11
Project: ironpython2   Author: IronLanguages   File: test_sys_setprofile.py    Apache License 2.0 5 votes vote down vote up
def test_empty(self):
        self.assertIsNone(sys.getprofile()) 
Example 12
Project: ironpython2   Author: IronLanguages   File: test_sys_setprofile.py    Apache License 2.0 5 votes vote down vote up
def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn) 
Example 13
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_sys_setprofile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_empty(self):
        self.assertIsNone(sys.getprofile()) 
Example 14
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_sys_setprofile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn) 
Example 15
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_sys_setprofile.py    GNU General Public License v2.0 5 votes vote down vote up
def test_empty(self):
        self.assertIsNone(sys.getprofile()) 
Example 16
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_sys_setprofile.py    GNU General Public License v2.0 5 votes vote down vote up
def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn) 
Example 17
Project: oss-ftp   Author: aliyun   File: test_sys_setprofile.py    MIT License 5 votes vote down vote up
def test_empty(self):
        self.assertIsNone(sys.getprofile()) 
Example 18
Project: oss-ftp   Author: aliyun   File: test_sys_setprofile.py    MIT License 5 votes vote down vote up
def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn) 
Example 19
Project: typin   Author: paulross   File: test_settrace.py    MIT License 5 votes vote down vote up
def __enter__(self):
        """
        Context manager sets the profiling function. This saves the existing
        tracing function.
        """
        self._trace_fn_stack.append(sys.gettrace())
        sys.settrace(self)
#         self._profile_fn_stack.append(sys.getprofile())
#         sys.setprofile(self)
        return self 
Example 20
Project: ppt   Author: rscohn2   File: __init__.py    MIT License 5 votes vote down vote up
def __enter__(self):
        self.old_dispatch = sys.getprofile()
        sys.setprofile(self.trace_dispatch)
        return self 
Example 21
Project: variety   Author: varietywalls   File: Util.py    GNU General Public License v3.0 5 votes vote down vote up
def stop(self):
        """
        Removes the module profiler globally and from future threads.
        """
        if sys.getprofile() != self.profiler:
            logger.warning(
                "ModuleProfiler: The currently enabled profile function was not ours - unbinding anyways"
            )
        threading.setprofile(None)
        sys.setprofile(None) 
Example 22
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_sys_setprofile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_empty(self):
        self.assertIsNone(sys.getprofile()) 
Example 23
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_sys_setprofile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn) 
Example 24
Project: cells   Author: AlesTsurko   File: test_sys_setprofile.py    MIT License 5 votes vote down vote up
def test_empty(self):
        self.assertIsNone(sys.getprofile()) 
Example 25
Project: cells   Author: AlesTsurko   File: test_sys_setprofile.py    MIT License 5 votes vote down vote up
def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn) 
Example 26
Project: Descent_py   Author: aadityachapagain   File: metaDecorator.py    MIT License 5 votes vote down vote up
def here_be_dragons(funct):  # create a decorator so we can, hm, enhance 'any' function
    def wrapper(*args, **kwargs):
        caller = inspect.getouterframes(inspect.currentframe())[1]  # pick up the caller
        parsed = ast.parse(caller[4][0], mode="single")  # parse the calling line
        arg_map = {}  # a map for our tracked args to establish global <=> local link
        for node in ast.walk(parsed):  # traverse the parsed code...
            # and look for a call to our wrapped function
            if isinstance(node, ast.Call) and node.func.id == funct.__name__:
                # loop through all positional arguments of the wrapped function
                for pos, var in enumerate(funct.func_code.co_varnames):
                    try:  # and try to find them in the captured call
                        if isinstance(node.args[pos], ast.Name):  # named argument!
                            arg_map[var] = node.args[pos].id  # add to our map
                    except IndexError:
                        break  # no more passed arguments
                break  # no need for further walking through the ast tree
        def trace(frame, evt, arg):  # a function to capture the wrapped locals
            if evt == "return":  # we're only interested in our function return
                for arg in arg_map:  # time to update our caller frame
                    caller[0].f_locals[arg_map[arg]] = frame.f_locals.get(arg, None)
        profile = sys.getprofile()  # in case something else is doing profiling
        sys.setprofile(trace)  # turn on profiling of the wrapped function
        try:
            return funct(*args, **kwargs)
        finally:
            sys.setprofile(profile)  # reset our profiling
    return wrapper


# Zap, there goes a pixie... Poor, poor, pixie. It will be missed. 
Example 27
Project: strict_functions   Author: CodyKochmann   File: trace2.py    MIT License 4 votes vote down vote up
def trace(fn=None, profiler=None):
    ''' This decorator allows you to visually trace
        the steps of a function as it executes to see
        what happens to the data as things are being
        processed.

        If you want to use a custom profiler, use the
        @trace(profiler=my_custom_profiler) syntax.

        Example Usage:

            def count_to(target):
               for i in range(1, target+1):
                   yield i

            @trace
            def sum_of_count(target):
               total = 0
               for i in count_to(target):
                   total += i
               return total

            sum_of_count(10)
    '''
    # analyze usage
    custom_profiler = fn is None and profiler is not None
    no_profiler = profiler is None and fn is not None
    no_args = profiler is None and fn is None
    # adjust for usage
    if custom_profiler: # for @trace(profiler=...)
        return partial(trace, profiler=profiler)
    elif no_args: # for @trace()
        return trace
    elif no_profiler: # for @trace
        profiler = default_profiler
    # validate input
    assert callable(fn)
    assert callable(profiler)
    # build the decorator
    @wraps(fn)
    def wrapper(*args, **kwargs):
        # flag for default_profiler to know to ignore this scope
        wafflestwaffles = None
        # save the previous profiler
        old_profiler = sys.getprofile()
        # set the new profiler
        sys.setprofile(profiler)
        try:
            # run the function
            return fn(*args, **kwargs)
        finally:
            # revert the profiler
            sys.setprofile(old_profiler)
    return wrapper 
Example 28
Project: strict_functions   Author: CodyKochmann   File: trace3.py    MIT License 4 votes vote down vote up
def trace(fn=None, profiler=None) -> Callable:
    ''' This decorator allows you to visually trace
        the steps of a function as it executes to see
        what happens to the data as things are being
        processed.

        If you want to use a custom profiler, use the
        @trace(profiler=my_custom_profiler) syntax.

        Example Usage:

            def count_to(target):
               for i in range(1, target+1):
                   yield i

            @trace
            def sum_of_count(target):
               total = 0
               for i in count_to(target):
                   total += i
               return total

            sum_of_count(10)
    '''
    # analyze usage
    custom_profiler = fn is None and profiler is not None
    no_profiler = profiler is None and fn is not None
    no_args = profiler is None and fn is None
    # adjust for usage
    if custom_profiler: # for @trace(profiler=...)
        return partial(trace, profiler=profiler)
    elif no_args: # for @trace()
        return trace
    elif no_profiler: # for @trace
        profiler = default_profiler
    # validate input
    assert callable(fn)
    assert callable(profiler)
    # build the decorator
    @wraps(fn)
    def wrapper(*args, **kwargs):
        # flag for default_profiler to know to ignore this scope
        wafflestwaffles = None
        # save the previous profiler
        old_profiler = sys.getprofile()
        # set the new profiler
        sys.setprofile(profiler)
        try:
            # run the function
            return fn(*args, **kwargs)
        finally:
            # revert the profiler
            sys.setprofile(old_profiler)
    return wrapper