【问题标题】:How to store the current state of InteractiveInterpreter Object in a database?如何将 InteractiveInterpreter 对象的当前状态存储在数据库中?
【发布时间】:2012-11-06 15:19:51
【问题描述】:

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

【问题讨论】:

    标签: python interactive-shell python-interactive


    【解决方案1】:

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

    【讨论】:

    • 我试过这个。但可悲的是,InteractiveInterpreter 是一个不可取的对象。
    【解决方案2】:

    好的,如果 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多