def run(filename, *, lineno: int, n: int = 2, show_lineno: bool = False): t = parse_string("".join(linecache.getlines(filename))) seen = [] targets = list(find_parents(select_node(t, lineno=lineno))) for i, node in enumerate(targets): target_lineno = node.get_lineno() if i == 0: start_lineno = target_lineno elif i == len(targets) - 1: start_lineno = max(1, target_lineno - n) else: start_lineno = target_lineno end_lineno = min(len(linecache.getlines(filename)) + 1, target_lineno + n + 1) if seen and start_lineno - seen[-1] > 1: if show_lineno: print(f"...") else: print("# ...") for lineno in range(start_lineno, end_lineno): if seen and lineno <= seen[-1]: continue seen.append(lineno) if show_lineno: print(f"{lineno:03d}: {linecache.getline(filename, lineno)}", end="") else: print(linecache.getline(filename, lineno), end="")
def run(filename, *, lineno: int, n: int = 2, show_lineno: bool = False): print("----------------------------------------") t = parse_string("".join(linecache.getlines(filename))) seen = [] list_of_target_lineno = list(rfind(t, lineno)) for i, target_lineno in enumerate(list_of_target_lineno): if i == 0: start_lineno = target_lineno elif i == len(list_of_target_lineno) - 1: start_lineno = max(1, target_lineno - n) else: start_lineno = target_lineno if i == len(list_of_target_lineno) - 1: end_lineno = target_lineno + 1 else: end_lineno = min( len(linecache.getlines(filename)) + 1, target_lineno + n + 1 ) if seen and start_lineno - seen[-1] > 1: if show_lineno: print(f"...") else: print("# ...") for lineno in range(start_lineno, end_lineno): if seen and lineno <= seen[-1]: continue seen.append(lineno) if show_lineno: print(f"{lineno:03d}: {linecache.getline(filename, lineno)}", end="") else: print(linecache.getline(filename, lineno), end="")
def run(filename, *, lineno: int): print("----------------------------------------") with open(filename) as rf: t = parse_string(rf.read()) for i in rfind(t, lineno): print(f"{i:03d}: {linecache.getline(filename, i)}", end="")
def run(code): print("----------------------------------------") print(code) t = parse_string(code) patch(t) print(t)
def transform_string(source: str): t = parse_string(source) return transform(t)
def replace_code_by_skeleton(base: str, skeleton: str) -> str: t0 = parse_string(base) t1 = parse_string(skeleton) return str(replace_ast_by_skeleton(t0, t1))
def lineno(x): return x.get_lineno() code = """ @profile def f(x): return x + 1 """ # DEBUG:pycomment.parse: visit_decorator (prefix='\n') # DEBUG:pycomment.parse: visit_AT (prefix='\n') # DEBUG:pycomment.parse: visit_NAME (prefix='') # DEBUG:pycomment.parse: visit_NEWLINE (prefix='') t = parse_string(code) for defs in run(t): for node in defs: node.prefix = "@profile\n" print(t) print("----------------------------------------", file=sys.stderr) code = """ def f(x): def g(y): return y + y return g(x + 1) """