2012-11-06 89 views
0

我正在尝试构建一个在线Python Shell。我通过创建InteractiveInterpreter的实例来执行命令,并使用命令runcode。为此,我需要将解释器状态存储在数据库中,以便跨命令使用全局名称空间和本地名称空间中的变量,函数,定义和其他值。有没有办法存储对象InteractiveInterpreter的当前状态,可以稍后检索并作为参数local传递给InteractiveInterpreter构造函数或者如果我不能这样做,还有什么替代方法可以实现上述功能?
下面是什么,我想实现如何在数据库中存储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) 
 

这里的伪代码,会是一个包含所有必要的信息表的一个实例。

回答

0

我相信pickle包应该适合你。您可以使用pickle.dumppickle.dumps来保存大多数对象的状态。 (然后pickle.loadpickle.loads把它找回来)

+0

我想这。但令人遗憾的是,InteractiveInterpreter是一个不可取消的ibject。 – gibraltar

0

好吧,如果泡菜不工作,你可以尝试重新实例化类,用格式(大约)象下面这样:

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 
相关问题