我有一个 while
循环,每次迭代都会获取一个新的数据集。在以下示例中,这是使用随机数生成器进行模拟的。我的 while
循环因按 Enter 键而中断。这是通过我发现的 heardEnter()
函数来实现的 here 。这非常有效。
但是,我还希望能够通过按键来保存我的数据,以防我不想退出循环。我想到的键是“s”键或空格键。我尝试使用 raw_input()
来实现此目的。然而,完成原始输入
所需的“Enter”使得与heardEnter
函数的组合变得麻烦。
一个最小的工作示例:
import sys
import numpy
import select
import matplotlib.pyplot as plt
def heardEnter():
i, o, e = select.select([sys.stdin], [], [], 0.0001)
for s in i:
if s == sys.stdin:
input = sys.stdin.readline()
return True
return False
x = numpy.linspace(0, 8*numpy.pi, 1000)
y = numpy.cos(x)
plt.ion()
plt.figure()
plt.plot(x, y)
plt.draw()
cont = True
while cont:
noise = numpy.random.normal(0, 1, len(y))
y_new = y + noise
plt.cla()
plt.plot(x, y_new)
plt.draw()
plt.pause(1.E-6)
if heardEnter():
cont = False
plt.close()
最佳答案
您应该修改您的 heardEnter
函数,使其不仅仅适用于 Enter
:
SAVE = 'save'
ENTER = 'enter'
def heardEnter():
i, o, e = select.select([sys.stdin], [], [], 0.0001)
for s in i:
if s == sys.stdin:
input = sys.stdin.readline()
if 's' in input:
return SAVE
else:
return ENTER
return None
然后在 while 循环中:
result = heard_enter()
if result == ENTER:
cont = False
plt.close()
elif result == SAVE:
# do save
由于 heardEnter
需要传达更多信息,因此我们不能再让它返回简单的 bool 值,而是使用常量作为返回值。这将使您将来也可以使用其他 key 。
关于python - 两次单独的按键来保存和退出 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31222614/