两次单独的击键来保存和退出 while 循环

Two seperate key strokes to save and quit a while loop

我有一个 while 循环,每次迭代都会获取一个新数据集。在以下示例中,这是使用随机数生成器模拟的。按回车键,我的 while 循环中断了。这是通过我发现hereheardEnter()函数实现的。这非常有效。

但是,我还希望能够在不想退出循环的情况下通过按键保存我的数据。我想到的键是 "s" 键或空格键。为此,我尝试使用 raw_input()。但是,最终确定 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 需要传达更多信息,我们不能再将其 return 设为简单的布尔值,而是使用常量作为 return 值。这将使您将来也可以使用其他键。