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

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

I want to use such an interactive Python shell (which runs inside the execution of my program) to test some internal program variables.

+47
python
Apr 08 2018-11-11T00:
source share
5 answers

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() 
+50
Apr 08 '11 at 16:15
source share

In ipython 0.13+ you need to do this:

 from IPython import embed embed() 
+13
May 23 '13 at
source share

I have had this code for a long time, hope you can use it.

To check / use variables, just put them in 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 want to strictly debug your application, I would suggest using IDE or pdb (python debugger) highly .

+6
Apr 08 '11 at 16:11
source share

With IPython, you just need to call:

 from IPython.Shell import IPShellEmbed; IPShellEmbed()() 
+5
Apr 08 2018-11-11T00:
source share

Another trick (besides already suggested ones) opens an interactive shell and imports your (possibly modified) python script. When importing, most variables, functions, classes, etc. are available. (Depending on how this is prepared), and you can even create objects interactively from the command line. So, if you have a test.py file, you can open Idle or another shell and type import test (if it is in the current working directory).

+1
May 13 '11 at 14:16
source share



All Articles