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

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

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.

回答1:

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


回答2:

In ipython 0.13+ you need to do this:

from IPython import embed  embed() 


回答3:

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



回答4:

Using IPython you just have to call:

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


回答5:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!