本文整理汇总了Python中sys.settrace函数的典型用法代码示例。如果您正苦于以下问题:Python settrace函数的具体用法?Python settrace怎么用?Python settrace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了settrace函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TraceFunc
def TraceFunc(self, frame, event, arg):
if event == 'call' and frame.f_code.co_name in ('schedule_cb', ):
sys.settrace(self.NullTraceFunc)
return self.ResumeTracingTraceFunc
tasklet = stackless.current
# print " TraceFunc: %s %s in %s, line %s" % \
# (id(tasklet), event, frame.f_code.co_name, frame.f_lineno)
ok = True
if event in ('call', 'line', 'return'):
key = (id(tasklet), frame.f_lineno)
try:
count = self.seen[key]
except KeyError:
ok = False
else:
self.seen[key] = count + 1
else:
ok = False
if not ok:
self.unexpected_trace_events.append((tasklet, event,
frame.f_code.co_name,
frame.f_lineno))
if event in ('call', 'line', 'exception'):
return self.TraceFunc
return None
示例2: run
def run(self):
# Note: this is important: we have to set the tracing function
# when the thread is started (we could set threading.settrace
# before starting this thread to do this externally)
try:
global call_finished
sys.settrace(do_nothing_trace_function)
exec self._Thread__kwargs['call_string'] in self._Thread__kwargs['kw']
print "exec call finished!"
call_finished = True
except TypeError as t:
call_finished = True
self._Thread__kwargs['Exception'] = t
except AttributeError as a:
call_finished = True
self._Thread__kwargs['Exception'] = a
except SyntaxError as s1:
call_finished = True
self._Thread__kwargs['Exception'] = s1
except SigFinish as sf1:
call_finished = True
self._Thread__kwargs['Exception'] = sf1
except Exception as e1:
call_finished = True
self._Thread__kwargs['Exception'] = e1
示例3: trace_process
def trace_process (**kwargs):
"""Literally log every line of python code as it runs.
Keyword arguments:
log -- file (name) to log to (default stderr)
scope -- base scope to log to (default Cobalt)"""
file_name = kwargs.get("log", None)
if file_name is not None:
log_file = open(file_name, "w")
else:
log_file = sys.stderr
scope = kwargs.get("scope", "Cobalt")
def traceit (frame, event, arg):
if event == "line":
lineno = frame.f_lineno
filename = frame.f_globals["__file__"]
if (filename.endswith(".pyc") or
filename.endswith(".pyo")):
filename = filename[:-1]
name = frame.f_globals["__name__"]
line = linecache.getline(filename, lineno)
print >> log_file, "%s:%s: %s" % (name, lineno, line.rstrip())
return traceit
sys.settrace(traceit)
示例4: unsettrace
def unsettrace(self, irc, msg, args):
"""takes no arguments
Stops tracing function calls on stdout.
"""
sys.settrace(None)
irc.replySuccess()
示例5: run_and_compare
def run_and_compare(self, func, events):
tracer = Tracer()
sys.settrace(tracer.trace)
func()
sys.settrace(None)
self.compare_events(func.func_code.co_firstlineno,
tracer.events, events)
示例6: main
def main():
usage = "mactrace.py [-o output_file_path] scriptfile [arg] ..."
parser = OptionParser(usage=usage)
parser.allow_interspersed_args = False
parser.add_option('-o', '--outfile', dest="outfile",
help="Save trace to <outfile>", default=None)
if not sys.argv[1:]:
parser.print_usage()
sys.exit(2)
(options, args) = parser.parse_args()
sys.argv[:] = args
if options.outfile:
twriter = TraceWriter(open(options.outfile, "w"))
else:
twriter = TraceWriter()
sys.settrace(twriter.trace)
if len(args) > 0:
progname = args[0]
sys.path.insert(0, os.path.dirname(progname))
with open(progname, 'rb') as fp:
code = compile(fp.read(), progname, 'exec')
globs = {
'__file__': progname,
'__name__': '__main__',
'__package__': None,
}
eval(code, globs)
else:
parser.print_usage()
return parser
示例7: __bootstrap
def __bootstrap(self):
try:
self._set_ident()
self._Thread__started.set()
threading._active_limbo_lock.acquire()
threading._active[self._Thread__ident] = self
del threading._limbo[self]
threading._active_limbo_lock.release()
if threading._trace_hook:
sys.settrace(threading._trace_hook)
if threading._profile_hook:
sys.setprofile(threading._profile_hook)
try:
self.run()
finally:
self._Thread__exc_clear()
finally:
with threading._active_limbo_lock:
self._Thread__stop()
try:
del threading._active[threading._get_ident()]
except:
pass
示例8: test_trace_raise_three_arg
def test_trace_raise_three_arg(self):
import sys
l = []
def trace(frame, event, arg):
if event == 'exception':
l.append(arg)
return trace
def g():
try:
raise Exception
except Exception as e:
import sys
raise Exception, e, sys.exc_info()[2]
def f():
try:
g()
except:
pass
sys.settrace(trace)
f()
sys.settrace(None)
assert len(l) == 2
assert issubclass(l[0][0], Exception)
assert issubclass(l[1][0], Exception)
示例9: test_set_unset_f_trace
def test_set_unset_f_trace(self):
import sys
seen = []
def trace1(frame, what, arg):
seen.append((1, frame, frame.f_lineno, what, arg))
return trace1
def trace2(frame, what, arg):
seen.append((2, frame, frame.f_lineno, what, arg))
return trace2
def set_the_trace(f):
f.f_trace = trace1
sys.settrace(trace2)
len(seen) # take one line: should not be traced
f = sys._getframe()
set_the_trace(f)
len(seen) # take one line: should not be traced
len(seen) # take one line: should not be traced
sys.settrace(None) # and this line should be the last line traced
len(seen) # take one line
del f.f_trace
len(seen) # take one line
firstline = set_the_trace.func_code.co_firstlineno
assert seen == [(1, f, firstline + 6, 'line', None),
(1, f, firstline + 7, 'line', None),
(1, f, firstline + 8, 'line', None)]
示例10: test_trace_return_exc
def test_trace_return_exc(self):
import sys
l = []
def trace(a,b,c):
if b in ('exception', 'return'):
l.append((b, c))
return trace
def g():
raise Exception
def f():
try:
g()
except:
pass
sys.settrace(trace)
f()
sys.settrace(None)
assert len(l) == 4
assert l[0][0] == 'exception'
assert isinstance(l[0][1][1], Exception)
assert l[1] == ('return', None)
assert l[2][0] == 'exception'
assert isinstance(l[2][1][1], Exception)
assert l[3] == ('return', None)
示例11: test_trace_try_finally
def test_trace_try_finally(self):
import sys
l = []
def trace(frame, event, arg):
if event == 'exception':
l.append(arg)
return trace
def g():
try:
raise Exception
finally:
pass
def f():
try:
g()
except:
pass
sys.settrace(trace)
f()
sys.settrace(None)
assert len(l) == 2
assert issubclass(l[0][0], Exception)
assert issubclass(l[1][0], Exception)
示例12: test_trace_hidden_prints
def test_trace_hidden_prints(self):
import sys
l = []
def trace(a,b,c):
l.append((a,b,c))
return trace
outputf = open(self.tempfile1, 'w')
def f():
print >> outputf, 1
print >> outputf, 2
print >> outputf, 3
return "that's the return value"
sys.settrace(trace)
f()
sys.settrace(None)
outputf.close()
# should get 1 "call", 3 "line" and 1 "return" events, and no call
# or return for the internal app-level implementation of 'print'
assert len(l) == 6
assert [what for (frame, what, arg) in l] == [
'call', 'line', 'line', 'line', 'line', 'return']
assert l[-1][2] == "that's the return value"
示例13: start
def start(self):
self.get_ready()
if self.nesting == 0: # pragma: no cover
sys.settrace(self.t)
if hasattr(threading, "settrace"):
threading.settrace(self.t)
self.nesting += 1
示例14: trace_lines
def trace_lines(do_trace):
"""Turn on/off printing each executed line.
Args:
do_trace: Whether to start tracing (True) or stop it (False).
"""
def trace(frame, event, arg):
"""Trace function passed to sys.settrace.
Return:
Itself, so tracing continues.
"""
if sys is not None:
loc = '{}:{}'.format(frame.f_code.co_filename, frame.f_lineno)
if arg is not None:
arg = utils.compact_text(str(arg), 200)
else:
arg = ''
print("{:11} {:80} {}".format(event, loc, arg), file=sys.stderr)
return trace
else:
# When tracing while shutting down, it seems sys can be None
# sometimes... if that's the case, we stop tracing.
return None
if do_trace:
sys.settrace(trace)
else:
sys.settrace(None)
示例15: __init__
def __init__(self, func=None, unpack=None, **kwargs):
self.__defs__ = []
self.__sizes__ = []
self.__attrs__ = []
self.__values__ = {}
self.__next__ = True
self.__baked__ = False
if func == None:
self.__format__()
else:
sys.settrace(self.__trace__)
func()
for name in func.func_code.co_varnames:
value = self.__frame__.f_locals[name]
self.__setattr__(name, value)
self.__baked__ = True
if unpack != None:
if isinstance(unpack, tuple):
self.unpack(*unpack)
else:
self.unpack(unpack)
if len(kwargs):
for name in kwargs:
self.__values__[name] = kwargs[name]