是否可以在Python程序中启动交互式Python Shell?
我想使用这样的交互式Python shell(在程序的执行内部运行)检查一些程序内部变量。
Answers:
该代码模块提供了一个交互式控制台:
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()
vars是一个内置函数。另外,在Python 3.5+中,您可以使用dict扩展从两个现有字典创建一个“ compound”字典variables = {**globals(), **locals()}。
readline似乎不再存在。向上/向下/历史记录功能是否仍可通过某些标准库使用?
我已经有很长时间了,希望您可以使用它。
要检查/使用变量,只需将其放入当前名称空间中即可。作为一个例子,我可以访问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()
但是,如果您想严格调试应用程序,我强烈建议您使用IDE或pdb(python debugger)。
使用IPython,您只需调用:
from IPython.Shell import IPShellEmbed; IPShellEmbed()()
import IPython; IPython.embed();。看到这个问题。
另一个技巧(除了已经建议的技巧之外)是打开一个交互式外壳并导入您的(可能是经过修改的)python脚本。导入后,大多数变量,函数,类等(取决于整个对象的准备方式)都可用,您甚至可以从命令行以交互方式创建对象。因此,如果您有test.py文件,则可以打开Idle或其他Shell,然后键入import test(如果它在当前工作目录中)。
exec(open("test.py").read())
print用于此目的。