在提示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
`
答案 0 :(得分:0)
您是否尝试过构建一个重现错误的最小工作示例?我在Windows上运行python,所以我无法尝试你正在做的一切,因为fcntl
是unix特定的,但我建议你开始删除部分代码(比如阅读和播放文件),直到错误消失。
此外,您正在打开文件和流,但从未明确地关闭它们,例如你打电话给stream = p.open(...)
,但没有stream.stop_stream()
和
stream.close()
,以及wf.close()
。这可能与您的错误无关,但最好是关闭文件而不是依赖垃圾回收。