如何在数据库中存储InteractiveInterpreter对象的当前状态?

时间:2012-11-06 15:19:51

标签: python interactive-shell python-interactive

我正在尝试构建一个在线Python Shell。我通过创建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是包含所有必要信息的表的实例。

2 个答案:

答案 0 :(得分:0)

我相信pickle包应该对你有用。您可以使用pickle.dumppickle.dumps来保存大多数对象的状态。 (然后pickle.loadpickle.loads将其取回)

答案 1 :(得分:0)

好的,如果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
相关问题