在运行 pylab 时,在 Matplotlib 中的事件处理期间无法使用 raw_input() -- 运行时错误:无法重新输入读取行



我正试图编写一个脚本,允许用户通过matplotlib中的事件处理来操作图形,但我需要让他们通过终端输入一些附加信息

调用raw_input()似乎破坏了脚本,并抛出RuntimeError: can't re-enter readline错误

这里有一段简单的代码来演示这一点:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))
def keypress(event):
print 'You press the "%s" key' %event.key
print 'is this true? Type yes or no'
y_or_n = raw_input()
cid = fig.canvas.mpl_connect('key_press_event', keypress)
plt.show()

如果我使用python运行它,这很好,但使用ipython-pylab会中断。不幸的是,我需要交互式模式

我看到其他人也遇到过这个问题,但我还没有看到的解决方案

您遇到了麻烦,因为matplotlib仍在侦听按键。不幸的是,简单地断开它的事件侦听对我来说并不起交互作用。然而,这个解决方案确实奏效了。尽管它限制了你不能使用"y"、"e"、"s"、"n"或"o"键。如果有必要的话,有一些变通办法。

import matplotlib.pyplot as plt
import numpy as np
#disable matplotlib keymaps
keyMaps = [key for key in plt.rcParams.keys() if 'keymap.' in key]
for keyMap in keyMaps:
plt.rcParams[keyMap] = ''
str = ''
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))
def keypress(event):
global str
if event.key in ['y','e','s','n','o']:
str += event.key
else:   
print 'You press the "%s" key' %event.key
print 'is this true? Type yes or no'
if str == 'yes':
print str
str = ''
elif str == 'no':
print str
str = ''
cid = fig.canvas.mpl_connect('key_press_event', keypress)
plt.show()

最新更新