sys.setprofile

Here are the examples of the python api sys.setprofile taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

31 Examples 7

Example 1

Project: imagrium Source File: test_profilehooks.py
def capture_events(callable, p=None):
    try:
        sys.setprofile()
    except TypeError:
        pass
    else:
        raise test_support.TestFailed(
            'sys.setprofile() did not raise TypeError')

    if p is None:
        p = HookWatcher()
    sys.setprofile(p.callback)
    protect(callable, p)
    sys.setprofile(None)
    return p.get_events()[1:-1]

Example 2

Project: PokemonGo-Bot-Desktop Source File: profile.py
Function: runctx
    def runctx(self, cmd, globals, locals):
        self.set_cmd(cmd)
        sys.setprofile(self.dispatcher)
        try:
            exec cmd in globals, locals
        finally:
            sys.setprofile(None)
        return self

Example 3

Project: PokemonGo-Bot-Desktop Source File: profile.py
Function: run_call
    def runcall(self, func, *args, **kw):
        self.set_cmd(repr(func))
        sys.setprofile(self.dispatcher)
        try:
            return func(*args, **kw)
        finally:
            sys.setprofile(None)

Example 4

Project: pymo Source File: test_sys_setprofile.py
Function: test_set_get
    def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        self.assertIs(sys.getprofile(), fn)

Example 5

Project: pymo Source File: test_sys_setprofile.py
def capture_events(callable, p=None):
    if p is None:
        p = HookWatcher()
    # Disable the garbage collector. This prevents __del__s from showing up in
    # traces.
    old_gc = gc.isenabled()
    gc.disable()
    try:
        sys.setprofile(p.callback)
        protect(callable, p)
        sys.setprofile(None)
    finally:
        if old_gc:
            gc.enable()
    return p.get_events()[1:-1]

Example 6

Project: pympler Source File: mprofile.py
Function: run
    def run(self, cmd):
        sys.setprofile(self.profile)
        try:
            exec(cmd)
        finally:
            sys.setprofile(None)
        return self

Example 7

Project: raiden Source File: profiler.py
def stop_profiler():
    # we keep the _state around for the user until the next session

    # Unregister the profiler in this order, otherwise we will have extra
    # measurements in the end
    sys.setprofile(None)
    threading.setprofile(None)
    greenlet.settrace(None)

Example 8

Project: ra Source File: pytest_.py
Function: trace_function
def trace_function(funcobj, *args, **kwargs):
    """Call a function, and return its locals"""
    funclocals = {}

    def _tracefunc(frame, event, arg):
        # Activate local trace for first call only
        if frame.f_back.f_locals.get('_tracefunc') == _tracefunc:
            if event == 'return':
                funclocals.update(frame.f_locals.copy())

    sys.setprofile(_tracefunc)
    try:
        funcobj(*args, **kwargs)
    finally:
        sys.setprofile(None)

    return funclocals

Example 9

Project: Eventlet Source File: profile.py
Function: start
    def start(self, name = "start"):
        if getattr(self, "running", False):
            return
        self._setup()
        self.simulate_call("start")
        self.running = True
        sys.setprofile(self.dispatcher)

Example 10

Project: imagrium Source File: test_profilehooks.py
Function: test_set_get
    @unittest.skip("FIXME: broken")
    def test_setget(self):
        def fn(*args):
            pass

        sys.setprofile(fn)
        assert sys.getprofile() == fn

Example 11

Project: TrustRouter Source File: profile.py
Function: runctx
    def runctx(self, cmd, globals, locals):
        self.set_cmd(cmd)
        sys.setprofile(self.dispatcher)
        try:
            exec(cmd, globals, locals)
        finally:
            sys.setprofile(None)
        return self

Example 12

Project: guv Source File: profile.py
Function: start
    def start(self, name="start"):
        if getattr(self, "running", False):
            return
        self._setup()
        self.simulate_call("start")
        self.running = True
        sys.setprofile(self.dispatcher)

Example 13

Project: profiling Source File: samplers.py
    def run(self, profiler):
        profile = functools.partial(self._profile, profiler)
        with deferral() as defer:
            sys.setprofile(profile)
            defer(sys.setprofile, None)
            threading.setprofile(profile)
            defer(threading.setprofile, None)
            yield

Example 14

Project: nvda Source File: watchdog.py
@ctypes.WINFUNCTYPE(None)
def _notifySendMessageCancelled():
	caller = inspect.currentframe().f_back
	if not caller:
		return
	# Set a profile function which will raise an exception when returning from the calling frame.
	def sendMessageCallCanceller(frame, event, arg):
		if frame == caller:
			# Raising an exception will also cause the profile function to be deactivated.
			raise CallCancelled
	sys.setprofile(sendMessageCallCanceller)

Example 15

Project: pikos Source File: test_profile_functions_manager.py
Function: test_preserving_previous_function
    def test_preserving_previous_function(self):

        sys.setprofile(self.bar)
        with self.monitor:
            self.foo()
        self.assertIs(sys.getprofile(), self.bar)

Example 16

Project: pikos Source File: profile_function_manager.py
    def recover(self):
        """ Unset the current function in the sys.setprofile.

        If available the previous method is recovered in setprofile. A
        RuntimeError is raised if the `previous` attribute does not exist.

        """
        if hasattr(self, 'previous'):
            sys.setprofile(self.previous)
            if has_threading:
                threading.setprofile(self.previous)
            del self.previous
        else:
            raise RuntimeError('A profile function has not been set')

Example 17

Project: pyinstrument Source File: profiler.py
Function: start
    def start(self):
        self.last_profile_time = timer()

        if self.use_signal:
            try:
                signal.signal(signal.SIGALRM, self._signal)
                # the following tells the system to restart interrupted system calls if they are
                # interrupted before any data has been transferred. This avoids many of the problems
                # related to signals interrupting system calls, see issue #16
                signal.siginterrupt(signal.SIGALRM, False)
            except ValueError:
                raise NotMainThreadError()

            signal.setitimer(signal.ITIMER_REAL, self.interval, 0.0)
        else:
            sys.setprofile(self._profile)

Example 18

Project: pyinstrument Source File: profiler.py
Function: stop
    def stop(self):
        if self.use_signal:
            signal.setitimer(signal.ITIMER_REAL, 0.0, 0.0)

            try:
                signal.signal(signal.SIGALRM, signal.SIG_IGN)
            except ValueError:
                raise NotMainThreadError()
        else:
            sys.setprofile(None)

Example 19

Project: ldaptor Source File: testutil.py
def calltrace():
    """Print out all function calls. For debug use only."""
    def printfuncnames(frame, event, arg):
        print "|%s: %s:%d:%s" % (event,
                                 frame.f_code.co_filename,
                                 frame.f_code.co_firstlineno,
                                 frame.f_code.co_name)
    import sys
    sys.setprofile(printfuncnames)

Example 20

Project: pymo Source File: test_sys_setprofile.py
Function: set_up
    def setUp(self):
        sys.setprofile(None)

Example 21

Project: pymo Source File: test_sys_setprofile.py
Function: tear_down
    def tearDown(self):
        sys.setprofile(None)

Example 22

Project: Eventlet Source File: profile.py
Function: stop
    def stop(self):
        sys.setprofile(None)
        self.running = False
        self.TallyTimings()

Example 23

Project: flappy-bird-py Source File: __init__.py
def _install_trace():
    sys.setprofile(_trace_func)

Example 24

Project: trtools Source File: profiler.py
Function: enter
    def __enter__(self):
        sys.setprofile(self.trace_dispatch)
        return self

Example 25

Project: trtools Source File: profiler.py
Function: exit
    def __exit__(self, type, value, traceback):
        sys.setprofile(None)

Example 26

Project: pybenchmark Source File: gprofiler.py
    def start(self):
        sys.setprofile(self._profile)
        self.started = timeit.default_timer()
        print("# Running in profile mode. #")

Example 27

Project: pybenchmark Source File: gprofiler.py
Function: stop
    @staticmethod
    def stop():
        sys.setprofile(None)
        print("# Profile mode stopped. #")

Example 28

Project: pikos Source File: test_profile_functions_manager.py
Function: tear_down
    def tearDown(self):
        sys.setprofile(self.old)

Example 29

Project: myhdl Source File: _extractHierarchy.py
Function: init
    def __init__(self, name, dut, *args, **kwargs):

        global _profileFunc
        _memInfoMap.clear()
        for hdl in _userCodeMap:
            _userCodeMap[hdl].clear()
        self.skipNames = ('always_comb', 'instance',
                          'always_seq', '_always_seq_decorator',
                          'always', '_always_decorator',
                          'instances',
                          'processes', 'posedge', 'negedge')
        self.skip = 0
        self.hierarchy = hierarchy = []
        self.absnames = absnames = {}
        self.level = 0

        _profileFunc = self.extractor
        sys.setprofile(_profileFunc)
        _top = dut(*args, **kwargs)
        sys.setprofile(None)
        if not hierarchy:
            raise ExtractHierarchyError(_error.NoInstances)

        self.top = _top

        # streamline hierarchy
        hierarchy.reverse()
        # walk the hierarchy to define relative and absolute names
        names = {}
        top_inst = hierarchy[0]
        obj, subs = top_inst.obj, top_inst.subs
        names[id(obj)] = name
        absnames[id(obj)] = name
        if not top_inst.level == 1:
            raise ExtractHierarchyError(_error.InconsistentToplevel % (top_inst.level, name))
        for inst in hierarchy:
            obj, subs = inst.obj, inst.subs
            if id(obj) not in names:
                raise ExtractHierarchyError(_error.InconsistentHierarchy)
            inst.name = names[id(obj)]
            tn = absnames[id(obj)]
            for sn, so in subs:
                names[id(so)] = sn
                absnames[id(so)] = "%s_%s" % (tn, sn)
                if isinstance(so, (tuple, list)):
                    for i, soi in enumerate(so):
                        sni = "%s_%s" % (sn, i)
                        names[id(soi)] = sni
                        absnames[id(soi)] = "%s_%s_%s" % (tn, sn, i)

Example 30

Project: myhdl Source File: _traceSignals.py
Function: call
    def __call__(self, dut, *args, **kwargs):
        global _tracing, vcdpath
        if isinstance(dut, _Block):
            # now we go bottom-up: so clean up and start over
            # TODO: consider a warning for the overruled block
            if _simulator._tracing:
                _simulator._tracing = 0
                _simulator._tf.close()
                os.remove(vcdpath)
        else:  # deprecated
            if _tracing:
                return dut(*args, **kwargs)  # skip
            else:
                # clean start
                sys.setprofile(None)

        from myhdl.conversion import _toVerilog
        if _toVerilog._converting:
            raise TraceSignalsError("Cannot use traceSignals while converting to Verilog")
        if not isinstance(dut, _Block):
            if not callable(dut):
                raise TraceSignalsError(_error.ArgType, "got %s" % type(dut))
        if _simulator._tracing:
            raise TraceSignalsError(_error.MultipleTraces)

        _tracing = 1
        try:
            if self.name is None:
                name = dut.__name__
                if isinstance(dut, _Block):
                    name = dut.func.__name__
            else:
                name = str(self.name)
            if name is None:
                raise TraceSignalsError(_error.TopLevelName)

            if self.directory is None:
                directory = ''
            else:
                directory = self.directory

            if isinstance(dut, _Block):
                h = _getHierarchy(name, dut)
            else:
                warnings.warn(
                    "\n    traceSignals(): Deprecated usage: See http://dev.myhdl.org/meps/mep-114.html", stacklevel=2)
                h = _HierExtr(name, dut, *args, **kwargs)

            if self.filename is None:
                filename = name
            else:
                filename = str(self.filename)

            vcdpath = os.path.join(directory, filename + ".vcd")

            if path.exists(vcdpath):
                backup = vcdpath + '.' + str(path.getmtime(vcdpath))
                shutil.copyfile(vcdpath, backup)
                os.remove(vcdpath)
            vcdfile = open(vcdpath, 'w')
            _simulator._tracing = 1
            _simulator._tf = vcdfile
            _writeVcdHeader(vcdfile, self.timescale)
            _writeVcdSigs(vcdfile, h.hierarchy, self.tracelists)
        finally:
            _tracing = 0

        return h.top

Example 31

Project: neubot Source File: __init__.py
Function: notify_event
    def notify_event(self, frame, event, arg):
        if event in ["call", "return"]:

            fname = self._getfilename(frame)
            func = frame.f_code.co_name

            if event == "return":
                self.frameno -= 1
                if not self.enabled and self.frameno == self.depth:
                    self.enabled = True
                if self.frameno < 0:
                    sys.setprofile(None)
                    return

            if self.enabled:
                lineno = frame.f_lineno
                prefix  = "    " * self.frameno
                buff = "%s%s %s:%d:%s()\n" % (prefix,event,fname,lineno,func)
                sys.stderr.write(buff)

            if event == "call":
                if self.enabled and fname.startswith("logging/"):
                    self.enabled = False
                    self.depth = self.frameno
                self.frameno += 1