0

在提示输入 raw_input 之后,我无法弄清楚如何在 while 循环的第二次迭代中避免 EOFError。我需要这个循环运行 30 次,理想情况下不会有一个 try-except 块来引导我从程序中启动。任何帮助将不胜感激!`

import sys
import pyaudio
import wave
import os
import fcntl
import time

def main():
    sound_cues = open('sound_cues').read().splitlines()
    light_cues = open('light_cues').read().splitlines()
    play_names = open('play_names').read().splitlines()
    plays = []

    for idx in range(len(play_names)):
        plays.append( {'name': play_names[idx], 'sound': sound_cues[idx], 'lights': light_cues[idx]} )

    while(True):
        play_num = raw_input("Enter a play number: ")

        play = plays[int(play_num) - 1]
        print
        print 'lights:'
        print play['lights']
        print
        raw_input("Press Enter to start sound...")
        print
        print 'sound:'
        print play['sound']

        audio = "sounds/" + play['sound']

        wf = wave.open(audio)
        p = pyaudio.PyAudio()
        stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = wf.getframerate(),
                output=True)

        data = wf.readframes(1024)
        fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
        fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
        print
        print "Press Enter to stop audio..."
        print
        while data != '':
            try:
                stdin = sys.stdin.read()
                if "\n" in stdin or "\r" in stdin:
                    break
            except IOError:
                pass
            stream.write(data)
            data = wf.readframes(1024)

if __name__ == "__main__":
    main()

`

输出是`

Enter a play number: 2

lights:
Black out, clamp light works as spot, follows Kris

Press Enter to start sound...

sound:
1.wav

Press Enter to stop audio...


Enter a play number: Traceback (most recent call last):
  File "30plays_1.py", line 56, in <module>
    main()
  File "30plays_1.py", line 18, in main
    play_num = raw_input("Enter a play number: ")
EOFError

`

4

1 回答 1

0

您是否尝试过构建一个重现错误的最小工作示例?我在 Windows 上运行 python,所以我不能尝试你正在做的所有事情,就像fcntlunix 特定的那样,但我建议你开始删除部分代码(比如读取和播放文件),直到错误消失。

此外,您正在打开文件和流但从未明确关闭它们,例如您正在调用stream = p.open(...),但没有stream.stop_stream()and 和 stream.close()no wf.close()。这可能与您的错误无关,但关闭文件而不依赖垃圾收集是一种好习惯。

于 2014-09-17T05:48:39.207 回答