是否可以在Python程序中启动交互式Python shell?
我想使用这样一个交互式Python shell(在我的程序执行中运行)来检查一些程序内部变量.
phi*_*hag 57
该代码模块提供了一个交互式控制台:
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()
Run Code Online (Sandbox Code Playgroud)
lub*_*osz 18
在ipython 0.13+中你需要这样做:
from IPython import embed
embed()
Run Code Online (Sandbox Code Playgroud)
我已经有了很长时间的代码,我希望你可以使用它.
要检查/使用变量,只需将它们放入当前命名空间即可.作为一个例子,我可以访问var1
并var2
从所述命令行.
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()
Run Code Online (Sandbox Code Playgroud)
但是,如果您想严格调试应用程序,我强烈建议使用IDE或pdb(python调试器).
使用IPython你只需要调用:
from IPython.Shell import IPShellEmbed; IPShellEmbed()()
Run Code Online (Sandbox Code Playgroud)