1 回答
TA贡献1111条经验 获得超0个赞
好吧,虽然花了一些功夫,但我明白了(woo):
import ast
import astor
import importlib
import sys
class trivial_transformer(ast.NodeTransformer):
def processImport(self, imp):
if imp not in sys.modules:
spec = importlib.util.find_spec(imp)
helper = importlib.util.module_from_spec(spec)
parsed_dep = ast.fix_missing_locations(self.visit(ast.parse(spec.loader.get_source(imp))))
exec(compile(parsed_dep, imp, 'exec'), helper.__dict__)
sys.modules[imp] = helper
def visit_ImportFrom(self, node):
self.processImport(node.module)
return node
def visit_Import(self, node):
for i in node.names:
self.processImport(i.name)
return node
def visit_FunctionDef(self, node):
body = []
for line in node.body:
body.append(
ast.Expr(
ast.Call(func=ast.Name('print', ctx=ast.Load()),
args=[ast.Str(s="Doing: "+astor.to_source(line).strip())],
keywords=[])))
body.append(self.generic_visit(line))
node.body = body
return node
init = 'a'
trivial_transformer().processImport(init)
import a
a.r(5)
添加回答
举报