0

I am trying to build an online Python Shell. I execute commands by creating an instance of InteractiveInterpreter and use the command runcode. For that I need to store the interpreter state in the database so that variables, functions, definitions and other values in the global and local namespaces can be used across commands. Is there a way to store the current state of the object InteractiveInterpreter that could be retrieved later and passed as an argument local to InteractiveInterpreter constructor or If I can't do this, what alternatives do I have to achieve the mentioned functionality?
Below is the pseudo code of what I am trying to achieve


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)

Here, session is an instance of table containing all the necessary information.

gibraltar
  • 1,678
  • 4
  • 20
  • 33

2 Answers2

0

I believe the pickle package should work for you. You can use pickle.dump or pickle.dumps to save the state of most objects. (then pickle.load or pickle.loads to get it back)

Cameron Sparr
  • 3,925
  • 2
  • 22
  • 31
0

Okay, if pickle doesn't work, you might try re-instantiating the class, with a format (roughly) like below:

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
Cameron Sparr
  • 3,925
  • 2
  • 22
  • 31