【问题标题】:Matplotlib Freezes When input() used in SpyderMatplotlib 在 Spyder 中使用 input() 时冻结
【发布时间】:2016-04-28 13:47:12
【问题描述】:

Windows 7。如果我在命令行打开一个普通的 ipython 终端,我可以输入:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4, 5])
plt.show(block=False)
input("Hello ")

但是如果我在 Spyder 中做同样的事情,只要我要求用户输入,Matplotlib 窗口就会冻结,所以我无法与之交互。我需要在提示显示时与情节进行交互。

在 Spyder 和普通控制台中,matplotlib.get_backend() 返回 'Qt4Agg'

编辑:为了澄清,我设置了 matplotlib,它显示在自己的窗口中,而不是嵌入为 PNG。 (我必须设置 Backend: Automatic 才能获得这种行为)

顺便说一句,在 Spyder 中,情节在 plt.plot() 之后立即打开。在常规控制台中,它仅在 plt.show() 之后打开。此外,如果我在 Spyder 中输入 input() 后按 Ctrl-C,整个控制台会意外挂起。比。在 IPython 中,它只是引发 KeyboardInterrupt 并将控制权返回给控制台。

编辑: 更完整的示例:在 IPython 控制台中工作,而不是在 Spyder 中(冻结)。想要根据用户输入移动情节。

import matplotlib.pyplot as pl

def anomaly_selection(indexes, fig, ax):
    selected = []

    for i in range(0, len(indexes)):
        index = indexes[i]
        ax.set_xlim(index-100, index+100)
        ax.autoscale_view()
        fig.canvas.draw()
        print("[%d/%d] Index %d " % (i, len(indexes), index), end="")
        while True:   
            response = input("Particle? ")
            if response == "y":
                selected.append(index)
                break
            elif response == "x":
                return selected
            elif response == "n":
                break

fig, ax = pl.subplots(2, sharex=True)
ax[0].plot([1, 2, 3, 4, 5]) # just pretend data
pl.show(block=False)

sel = anomaly_selection([100, 1000, 53000, 4300], fig, ax[0])

大量编辑:我认为这是 input() 阻塞 Qt 的问题。如果这个问题没有引起关注,我的解决方法是构建一个嵌入了 Matplotlib 图的 Qt 窗口,并通过窗口获取键盘输入。

【问题讨论】:

  • 另外,真的有人使用 Spyder 吗?我应该使用其他东西来替代 MATLAB 吗?我主要想使用 Python 作为一种更健全的语言来构建更大的数值应用程序,但要留在更具实验性的 MATLAB 风格的环境中。
  • (Spyder dev here) Spyder 有很多用户,不知道有多少,但我们每年有大约 200.000 次下载。
  • 请发布您正在使用的代码的简单版本,以便我们了解您想要实现的目标。您发布的伪代码(尤其是 GOTO 2 步骤)是不够的。谢谢:-)
  • 您好,我发布了一个确切的命令序列,并描述了它们起作用和不起作用的情况。我想在命令行接受用户输入,同时还显示 matplotlib 图。
  • 我正在使用(并且喜欢)spyder。在 Ubuntu 上,我可以重现上述行为。一旦给出输入,窗口就会再次做出反应。

标签: python matplotlib ipython spyder


【解决方案1】:

比我更了解的人,如果可能的话,请发表一个答案。我对 Python/Scipy/Spyder 知之甚少

这是我编写的一个 kludgy 模块,它可以防止 Matplotlib 窗口在 Spyder 下的 input() 挂起时冻结。

您必须事先调用prompt_hack.start(),之后调用prompt_hack.finish(),并将input()替换为prompt_hack.input()

prompt_hack.py

import matplotlib.pyplot
import time
import threading

# Super Hacky Way of Getting input() to work in Spyder with Matplotlib open
# No efforts made towards thread saftey!

prompt = False
promptText = ""
done = False
waiting = False
response = ""

regular_input = input

def threadfunc():
    global prompt
    global done
    global waiting
    global response

    while not done:   
        if prompt:   
            prompt = False
            response = regular_input(promptText)
            waiting = True
        time.sleep(0.1)

def input(text):
    global waiting
    global prompt
    global promptText

    promptText = text
    prompt = True

    while not waiting:
        matplotlib.pyplot.pause(0.01)
    waiting = False

    return response

def start():
    thread = threading.Thread(target = threadfunc)
    thread.start()

def finish():
    global done
    done = True

【讨论】:

  • 谢谢。这只是为我省去了很多麻烦。对于任何尝试使用它来多次调用 input() 的人,请确保在 start() 调用中重置所有全局变量。
【解决方案2】:

经过大量挖掘后,我得出的结论是,您应该制作一个 GUI。我建议你使用 PySide 或 PyQt。为了让 matplotlib 有一个图形窗口,它运行一个事件循环。任何单击或鼠标移动都会触发一个事件,该事件会触发图形部分执行某些操作。脚本的问题在于每一段代码都是顶级的。它表明代码是按顺序运行的。

当您手动将代码输入到 ipython 控制台时,它可以工作!这是因为 ipython 已经启动了一个 GUI 事件循环。您调用的每个命令都在事件循环中处理,从而允许其他事件发生。

您应该创建一个 GUI 并将该 GUI 后端声明为相同的 matplotlib 后端。如果您有一个按钮单击触发 anomaly_selection 函数,则该函数在单独的线程中运行,并且应该允许您仍然在 GUI 中进行交互。

通过大量的摆弄和移动调用函数的方式,你可以让 thread_input 函数工作。

幸运的是,PySide 和 PyQt 允许您手动调用来处理 GUI 事件。我添加了一个方法,该方法要求在单独的线程中输入并循环等待结果。当它等待时,它告诉 GUI 处理事件。如果您安装了 PySide(或 PyQt)并将其用作 matplotlib 的后端,return_input 方法有望起作用。

import threading

def _get_input(msg, func):
    """Get input and run the function."""
    value = input(msg)
    if func is not None:
        func(value)
    return value
# end _get_input

def thread_input(msg="", func=None):
    """Collect input from the user without blocking. Call the given function when the input has been received.

    Args:
        msg (str): Message to tell the user.
        func (function): Callback function that will be called when the user gives input.
    """
    th = threading.Thread(target=_get_input, args=(msg, func))
    th.daemon = True
    th.start()
# end thread_input

def return_input(msg=""):
    """Run the input method in a separate thread, and return the input."""
    results = []
    th = threading.Thread(target=_store_input, args=(msg, results))
    th.daemon = True
    th.start()
    while len(results) == 0:
        QtGui.qApp.processEvents()
        time.sleep(0.1)

    return results[0]
# end return_input

if __name__ == "__main__":

    stop = [False]
    def stop_print(value):
        print(repr(value))
        if value == "q":
            stop[0] = True
            return
        thread_input("Enter value:", stop_print)

    thread_input("Enter value:", stop_print)
    add = 0
    while True:
        add += 1
        if stop[0]:
            break

    print("Total value:", add)

这段代码似乎对我有用。虽然它确实给了我一些关于 ipython 内核的问题。

from matplotlib import pyplot as pl

import threading


def anomaly_selection(selected, indexes, fig, ax):
    for i in range(0, len(indexes)):
        index = indexes[i]
        ax.set_xlim(index-100, index+100)
        ax.autoscale_view()
        #fig.canvas.draw_idle() # Do not need because of pause
        print("[%d/%d] Index %d " % (i, len(indexes), index), end="")
        while True:
            response = input("Particle? ")
            if response == "y":
                selected.append(index)
                break
            elif response == "x":
                selected[0] = True
                return selected
            elif response == "n":
                break

    selected[0] = True
    return selected


fig, ax = pl.subplots(2, sharex=True)
ax[0].plot([1, 2, 3, 4, 5]) # just pretend data
pl.show(block=False)

sel = [False]
th = threading.Thread(target=anomaly_selection, args=(sel, [100, 1000, 53000, 4300], fig, ax[0]))
th.start()
#sel = anomaly_selection([100, 1000, 53000, 4300], fig, ax[0])


while not sel[0]:
    pl.pause(1)
th.join()

【讨论】:

  • 这个例子不起作用。这是仅从 Spyder 运行的 Matplotlib 的问题。如问题中所述,交互模式也已启用。我用线程中的用户输入做了一个类似的例子,但关键是在循环中调用 pyplot.pause() 以便 matplotlib 窗口不会冻结。如果你能以某种方式解决这个问题,那么你的答案似乎比我的更精致。
  • 我建议你只做一个GUI。无论如何,您正在申请。脚本应该只用于小型快速运行。如果您使用的是 PyQt 后端,我添加了 return_input 方法,它有望工作。我编辑了我的答案以解释事情是如何运作的。
  • 我同意你的观点,但这应该是一次性的。用户不必为了在循环中抓取键盘输入而了解 Qt 事件循环。在 MATLAB 中,这不是问题。 IMO 这应该在错误报告中,尽管它是架构的副作用。
  • 等着看 Spyder 开发者@CarlosCordoba 有没有什么建议再选择这个答案。
  • 我决定再次解决这个问题并让它为你工作。上面发布的新代码。
猜你喜欢
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2016-08-09
  • 2017-08-19
相关资源
最近更新 更多