我正在尝试构建一个在线python shell。我通过创建InteractiveInterpreter
实例并使用命令runcode
来执行命令。为此,我需要将解释器状态存储在数据库中,以便可以在命令上使用变量,函数,定义和其他值。有没有办法存储对象InteractiveInterpreter
的当前状态,该对象的当前状态可以在以后检索并作为参数local
传递给InteractiveInterpreter
构造函数,或者如果我不能这样做,我必须采取什么替代方案才能实现上述功能?<<br/>以下是我要实现的伪代码
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)
在这里,会话是包含所有必要信息的表的实例。
我相信pickle
软件包应该适合您。您可以使用pickle.dump
或pickle.dumps
来保存大多数对象的状态。(然后pickle.load
或pickle.loads
将其恢复)
好吧,如果泡菜不起作用,您可以尝试使用类似于下面的格式(粗略)重新构成班级:
: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