假设我们有一个临时文件,可以向其中写入一些输出。但出于某种奇怪的原因,我们希望通过一些归档技术(例如 tar)对其进行压缩,
我所说的 tempfile 是指没有由 tempfile.TemporaryFile() 创建的可见名称的文件。有任何想法吗?我的第一印象包括一些调整和类继承..有没有更简单的方法?
我很感激能学到一些有用的东西,至于现在,我一直在盲目行动。所以问题出在python的ast.NodeTransformer. 我想知道是否可以使用这种方式向现有类添加一个函数,而不是生气。
这就是我到目前为止的处理方式。
import ast, inspect, cla # cla is a name of class to which we want to add a new function
klass = inspect.getsource(cla)
tree = ast.parse(klass)
st = '''def function(): return 1'''
Foo = ast.parse(st)
class AddFunc(ast.NodeTransformer):
def visit_ClassDef(self, node):
return node, node.body + Foo.body
self.generic_visit(node)
inst = AddFunc()
stuff = i.visit(tree)
# now the trouble begins, a compiling..
co = compile(stuff, filename='<ast>', mode='exec')
# i get TypeError: required "lineno" missing from stmt
Run Code Online (Sandbox Code Playgroud)
我已经尝试过(如您可能猜到的那样不成功)通过使用 ast …