【发布时间】:2017-07-10 01:04:59
【问题描述】:
我是一个 python 初学者,我尝试获取一个网络收音机并将流保存在一个文件中。我想在一段时间后刷新内容(例如只保留 1 小时的流)。所以我不会把所有的流都写在一个文件中,我会尝试将流存储在多个文件中(output_1.bin 一分钟,output_2.bin 下一分钟……)
但我无法正确退出“for”。 exit() 不是为了这个目的?
def download_file(url):
r = requests.get(url, stream=True)
i = 1
while True:
local_filename = "output_"+str(i)+".bin"
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
i = i+1
print("iteration",i,"and modulo result :",i % 10,"\n")
if i % 10 == 0:
exit()
f.close()
print("Am I out of the for ?")
return local_filename
download_file('http://direct.franceinfo.fr/live/franceinfo-lofi.mp3')
【问题讨论】:
-
exit()退出进程。你可能想要break。 -
我想你可能正在寻找 break 命令而不是 exit()
-
顺便说一句,即使退出进程也不应该在脚本中使用
exit()(它仅用于交互使用),而应使用sys.exit()。 -
...而您的
while循环也没有退出条件。
标签: python file for-loop stream