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.
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.
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()
In ipython 0.13+ you need to do this:
from IPython import embed
embed()
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).
Using IPython you just have to call:
from IPython.Shell import IPShellEmbed; IPShellEmbed()()
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).