【发布时间】:2021-09-10 10:07:41
【问题描述】:
进一步阅读this post我们如何从pickle文件中获取源代码
我尝试使用getsource(在阅读this post 之后),但只有在同一会话中定义类时才有效,下面是我尝试过的代码
class Foo(object):
def bar(self, x):
return self.y + x
def __init__(self, y):
self.y = y
import dill
f = Foo(5)
with open('foo.pkl', 'wb') as pkl:
dill.dump(f, pkl)
with open('foo.pkl', 'rb') as pkl:
b = dill.load(pkl)
print(b)
#sFoo = dill.source.getsource('foo.pkl') ## error
#sFoo = dill.source.getsource(b) ## error
#sFoo = dill.source.getsource(b.bar) ## error
错误详情
使用sFoo = dill.source.getsource(b) 时错误为OSError: could not extract source code
当使用sFoo = dill.source.getsource(b.bar) 时错误为OSError: could not extract source code
【问题讨论】:
-
这将有助于查看您遇到的错误。您的第一次和第三次尝试似乎是由于以非预期方式使用该功能。
getsource从对象中提取代码,因此在foo.pkl上调用它没有意义。同样,如果你正在转储f.bar,那么在加载之后,b应该是f.bar的副本......所以b.bar没有意义,应该是属性错误或类似的。 -
您好迈克,感谢您的评论。我已经更新了我得到的错误。我同意首先不正确使用
getsource。现在不是转储f.bar,而是将其更改为f如果getsource不是合法方式,还有其他方法可以检索源代码吗? -
getsource是完全合法的获取代码的方式。