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

Python

Python Problem Overview


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 program's execution) to inspect some program-internal variables.

Python Solutions


Solution 1 - Python

The http://docs.python.org/library/code.html">code</a> 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()

Solution 2 - Python

In ipython 0.13+ you need to do this:

from IPython import embed

embed()

Solution 3 - Python

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).

Solution 4 - Python

Using IPython you just have to call:

from IPython.Shell import IPShellEmbed; IPShellEmbed()()

Solution 5 - Python

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzJayView Question on Stackoverflow
Solution 1 - PythonphihagView Answer on Stackoverflow
Solution 2 - PythonluboszView Answer on Stackoverflow
Solution 3 - PythonMike LewisView Answer on Stackoverflow
Solution 4 - PythonFábio DinizView Answer on Stackoverflow
Solution 5 - PythonheltonbikerView Answer on Stackoverflow