gpt4 book ai didi

python - 在 Spyder 中使用 input() 时 Matplotlib 卡住

转载 作者:太空狗 更新时间:2023-10-30 02:58:10 30 4
gpt4 key购买 nike

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 窗口,然后通过该窗口获取键盘输入。

最佳答案

比我更了解的人,请尽可能发布答案。我对 Python/Scipy/Spyder 知之甚少

这是我编写的一个笨拙的模块,它可以防止 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

关于python - 在 Spyder 中使用 input() 时 Matplotlib 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938593/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com