有没有办法以编程方式强制 Python 脚本在执行过程中的任意点放入 REPL,即使脚本是从命令行启动的?
我正在编写一个快速而肮脏的绘图程序,我想从标准输入或文件中读取数据,绘制它,然后放入 REPL 中以允许自定义绘图。
我经常用这个:
def interact():
import code
code.InteractiveConsole(locals=globals()).interact()
您可以尝试使用 python 的交互式选项:
python -i program.py
这将执行program.py中的代码,然后转到REPL。您在program.py顶层定义或导入的任何内容都将可用。
您应该这样做(IPython > v0.11):
import IPython
IPython.embed()
对于 IPython <= v0.11:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # this call anywhere in your program will start IPython
您应该使用 IPython,Python REPL 中的凯迪拉克。请参阅 http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython
来自文档:
它在科学方面也很有用 计算情况 通常需要做一些自动的事情, 计算密集型部分和 然后停下来查看数据、图表等。 打开 IPython 实例将给出 您可以完全访问您的数据并且 功能,并且可以恢复程序 一旦你完成了执行 互动部分(也许停止 稍后再次,根据需要多次)。
您可以启动调试器:
import pdb;pdb.set_trace()
不确定您想要 REPL 的用途,但调试器非常相似。
我只是在我自己的一个脚本中执行了此操作(它在一个自动化框架内运行,该框架是一个巨大的 PITA 工具):
x = 0 # exit loop counter
while x == 0:
user_input = raw_input("Please enter a command, or press q to quit: ")
if user_input[0] == "q":
x = 1
else:
try:
print eval(user_input)
except:
print "I can't do that, Dave."
continue
只需将其放置在您想要断点的任何位置,您就可以使用与 python 解释器相同的语法检查状态(尽管它似乎不允许您进行模块导入)。 它不是很优雅,但不需要任何其他设置。
上面的答案很好,但是如果您希望在 IDE 中使用此功能。将 Visual Studio Code (v1.5.*) 与 Python 设置结合使用:
right click
,然后从下拉菜单中选择 Run Selection/Line in Interactive Window
。shift + enter
。Python
文件,然后选择 Run Current File in Interactive Window
这将启动一个交互式会话,包括 linting、代码完成和语法突出显示:
输入您要评估的代码,然后按键盘上的
shift + enter
执行。
享受Python!
此函数对调用者的局部变量和全局变量执行
code.interact
操作:
def repl():
"""This starts a REPL with the callers globals and locals available
Raises:
RuntimeError: Is raised when the callers frame is not available
"""
import code
import inspect
frame = inspect.currentframe()
if not frame:
raise RuntimeError('No caller frame')
code.interact(local=dict(frame.f_back.f_globals, **frame.f_back.f_locals))