如何从 Python 代码放入 REPL(读取、评估、打印、循环)

发布于 2024-08-04 09:02:55 字数 128 浏览 2 评论 0原文

有没有办法以编程方式强制 Python 脚本在执行过程中的任意点放入 REPL,即使该脚本是从命令行启动的?

我正在编写一个快速而肮脏的绘图程序,我想从标准输入或文件中读取数据,绘制它,然后放入 REPL 中以允许自定义绘图。

Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?

I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

并安 2024-08-11 09:02:55

我经常使用这个:

def interact():
    import code
    code.InteractiveConsole(locals=globals()).interact()

I frequently use this:

def interact():
    import code
    code.InteractiveConsole(locals=globals()).interact()
枯叶蝶 2024-08-11 09:02:55

您可以尝试使用Python的交互式选项:

python -i program.py

这将执行program.py中的代码,然后转到REPL。您在program.py 顶层定义或导入的任何内容都将可用。

You could try using the interactive option for python:

python -i program.py

This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.

别在捏我脸啦 2024-08-11 09:02:55

下面是你应该如何做的(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 实例将给出
您可以完全访问您的数据并且
功能,并且可以恢复程序
一旦你完成了执行
互动部分(也许停止
稍后再重复一次,根据需要多次)。

Here's how you should do it (IPython > v0.11):

import IPython
IPython.embed()

For IPython <= v0.11:

from IPython.Shell import IPShellEmbed

ipshell = IPShellEmbed()

ipshell() # this call anywhere in your program will start IPython

You should use IPython, the Cadillac of Python REPLs. See http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython

From the documentation:

It can also be useful in scientific
computing situations where it is
common to need to do some automatic,
computationally intensive part and
then stop to look at data, plots, etc.
Opening an IPython instance will give
you full access to your data and
functions, and you can resume program
execution once you are done with the
interactive part (perhaps to stop
again later, as many times as needed).

李白 2024-08-11 09:02:55

您可以启动调试器:

import pdb;pdb.set_trace() 

不确定您想要 REPL 的用途,但调试器非常相似。

You can launch the debugger:

import pdb;pdb.set_trace() 

Not sure what you want the REPL for, but the debugger is very similar.

九局 2024-08-11 09:02:55

要使用 iPython 和调试器的功能,您应该使用 ipdb

您可以以与 pdb 相同的方式使用它,但添加:

import ipdb
ipdb.set_trace()

To get use of iPython and functionality of debugger you should use ipdb,

You can use it in the same way as pdb, with the addition of :

import ipdb
ipdb.set_trace()
夜巴黎 2024-08-11 09:02:55

我只是在我自己的一个脚本中执行了此操作(它在一个自动化框架内运行,该框架是一个巨大的 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 解释器相同的语法检查状态(尽管它似乎不允许您进行模块导入)。
它不是很优雅,但不需要任何其他设置。

I just did this in one of my own scripts (it runs inside an automation framework that is a huge PITA to instrument):

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

Just place this wherever you want a breakpoint, and you can check the state using the same syntax as the python interpreter (although it doesn't seem to let you do module imports).
It's not very elegant, but it doesn't require any other setup.

[旋木] 2024-08-11 09:02:55

上面的答案很好,但是如果您希望在 IDE 中使用此功能。将 Visual Studio Code (v1.5.*) 与 Python 设置

  1. 突出显示您要运行的行,然后
  • 右键单击并选择运行选择/行从下拉列表中的交互窗口中。
  • 按键盘上的 shift + Enter

输入图片此处描述

  1. 右键单击​​要在文件资源管理器中执行的 Python 文件,然后选择在交互窗口中运行当前文件

在此处输入图像描述

这将启动一个交互式会话,包括 linting、代码完成和语法突出显示:

在此处输入图像描述

在此处输入图像描述

输入您要评估的代码,然后按 shift +在键盘上输入来执行。

享受Python!

Great answers above, but if you would like this functionality in your IDE. Using Visual Studio Code (v1.5.*) with Python Setup:

  1. Highlight the lines you would like to run and
  • right click and select Run Selection/Line in Interactive Window from the drop down.
  • Press shift + enter on your keyboard.

enter image description here

  1. Right click on the Python file you want to execute in the file explorer and select Run Current File in Interactive Window

enter image description here

This will launch an interactive session, with linting, code completion and syntax highlighting:

enter image description here

enter image description here

Enter the code you would like to evaluate, and hit shift + enter on your keyboard to execute.

Enjoy Python!

美人骨 2024-08-11 09:02:55

该函数与调用者的局部变量和全局变量进行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))

This function does code.interact with the locals and globals of the caller:

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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文