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

前端 未结 5 931
鱼传尺愫
鱼传尺愫 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:18

    The code module provides an interactive console:

    import readline # optional, will allow Up/Down/History in the console
    import code
    variables = globals().copy()
    variables.update(locals())
    shell = code.InteractiveConsole(variables)
    shell.interact()
    
    0 讨论(0)
  • 2020-12-07 09:18

    In ipython 0.13+ you need to do this:

    from IPython import embed
    
    embed()
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-07 09:28

    Using IPython you just have to call:

    from IPython.Shell import IPShellEmbed; IPShellEmbed()()
    
    0 讨论(0)
  • 2020-12-07 09:31

    Another trick (besides the ones already suggested) is opening an interactive shell and importing your (perhaps modified) python script. Upon importing, most of the variables, functions, classes and so on (depending on how the whole thing is prepared) are available, and you could even create objects interactively from command line. So, if you have a test.py file, you could open Idle or other shell, and type import test (if it is in current working directory).

    0 讨论(0)
提交回复
热议问题