Python 如何在数据库中存储InteractiveInterpreter对象的当前状态?
我正在尝试构建一个在线Python Shell。我通过创建Python 如何在数据库中存储InteractiveInterpreter对象的当前状态?,python,interactive-shell,python-interactive,Python,Interactive Shell,Python Interactive,我正在尝试构建一个在线Python Shell。我通过创建InteractiveInterpreter的实例来执行命令,并使用命令runcode。为此,我需要将解释器状态存储在数据库中,以便可以跨命令使用全局和本地名称空间中的变量、函数、定义和其他值。是否有一种方法可以存储对象的当前状态InteractiveInterpreter,该状态可以在以后检索并作为参数local传递给InteractiveInterpreter构造函数,或者如果我不能这样做,我需要什么替代方法来实现上述功能? 下面是我
InteractiveInterpreter
的实例来执行命令,并使用命令runcode
。为此,我需要将解释器状态存储在数据库中,以便可以跨命令使用全局和本地名称空间中的变量、函数、定义和其他值。是否有一种方法可以存储对象的当前状态InteractiveInterpreter
,该状态可以在以后检索并作为参数local
传递给InteractiveInterpreter
构造函数,或者如果我不能这样做,我需要什么替代方法来实现上述功能?下面是我试图实现的伪代码
def fun(code, sessionID):
session = Session()
# get the latest state of the interpreter object corresponding to SessionID
vars = session.getvars(sessionID)
it = InteractiveInterpreter(vars)
it.runcode(code)
#save back the new state of the interpreter object
session.setvars(it.getState(),sessionID)
这里,session是包含所有必要信息的表的一个实例。我相信
pickle
包应该适合您。您可以使用pickle.dump
或pickle.dumps
保存大多数对象的状态。(然后pickle.load
或pickle.load
将其取回)好的,如果pickle不起作用,您可以尝试重新实例化该类,格式(大致)如下:
class MyClass:
def __init__(self, OldClass):
for d in dir(OldClass):
# go through the attributes from the old class and set
# the new attributes to what you need
我试过这个。但遗憾的是,InteractiveInterpreter是一个不可点击的对象。