2012-11-06 31 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 
相關問題