Embed (create) an interactive Python shell inside a Python program

前端 未结 5 933
鱼传尺愫
鱼传尺愫 2020-12-07 08:39

Is it possible to start an interactive Python shell inside a Python program?

I want to use such an interactive Python shell (which is running inside my prog

5条回答
  •  無奈伤痛
    2020-12-07 09:19

    I've had this code for a long time, I hope you can put it to use.

    To inspect/use variables, just put them into the current namespace. As an example, I can access var1 and var2 from the command line.

    var1 = 5
    var2 = "Mike"
    # Credit to effbot.org/librarybook/code.htm for loading variables into current namespace
    def keyboard(banner=None):
        import code, sys
    
        # use exception trick to pick up the current frame
        try:
            raise None
        except:
            frame = sys.exc_info()[2].tb_frame.f_back
    
        # evaluate commands in current namespace
        namespace = frame.f_globals.copy()
        namespace.update(frame.f_locals)
    
        code.interact(banner=banner, local=namespace)
    
    
    if __name__ == '__main__':
      keyboard()
    

    However if you wanted to strictly debug your application, I'd highly suggest using an IDE or pdb(python debugger).

提交回复
热议问题