我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.getblock()。
def get_annotated_lines(self): """Helper function that returns lines with extra information.""" lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)] # find function definition and mark lines if hasattr(self.code, 'co_firstlineno'): lineno = self.code.co_firstlineno - 1 while lineno > 0: if _funcdef_re.match(lines[lineno].code): break lineno -= 1 try: offset = len(inspect.getblock([x.code + '\n' for x in lines[lineno:]])) except TokenError: offset = 0 for line in lines[lineno:lineno + offset]: line.in_frame = True # mark current line try: lines[self.lineno - 1].current = True except IndexError: pass return lines
def write_text(self, stream): if not path.exists(self.filename): stream.write("ERROR: %s\n" % self.filename) return stream.write("File: %s\n" % self.filename) stream.write("Name: %s\n" % self.name) stream.write("Total time: %g [sec]\n" % self.total_time) linecache.clearcache() lines = linecache.getlines(self.filename) if self.name != "<module>": lines = inspect.getblock(lines[self.firstlineno - 1:]) template = '%6s %9s %12s %-s' header = template % ("Line", "Hits", "Time", "Code") stream.write(header) stream.write("\n") stream.write("=" * len(header)) stream.write("\n") d = {} for i, code in zip(itertools.count(self.firstlineno), lines): timing = self.timings.get(i) if timing is None: d[i] = { "hits": "", "time": "", "code": code } else: d[i] = { "hits": timing.n_hits, "time": timing.total_time, "code": code } for i in sorted(d.keys()): r = d[i] stream.write(template % (i, r["hits"], r["time"], r["code"])) stream.write("\n")
def getsourcelines(self, obj): lines, lineno = inspect.findsource(obj) if inspect.isframe(obj) and obj.f_globals is obj.f_locals: # must be a module frame: do not try to cut a block out of it return lines, 1 elif inspect.ismodule(obj): return lines, 1 return inspect.getblock(lines[lineno:]), lineno+1
def getsourcelines(obj): lines, lineno = inspect.findsource(obj) if inspect.isframe(obj) and obj.f_globals is obj.f_locals: # must be a module frame: do not try to cut a block out of it return lines, 1 elif inspect.ismodule(obj): return lines, 1 return inspect.getblock(lines[lineno:]), lineno+1