python - 在一小时后 X 分钟时中断请求流
问题描述
对不起,这里的菜鸟问题。我正在尝试从早上 6 点到早上 6:30 录制一个互联网广播电台,但我不知道如何停止请求流。假设这个脚本计划在早上 6 点运行。
import requests
import time
r = requests.get(stream_url, stream=True) #not putting url here but it's defined
with open('6am-630am.mp3', 'wb') as f:
try:
while int(time.strftime('%M')) < 30: #do this till it's 30 mins past hour
for block in r.iter_content(1024):
f.write(block)
except KeyboardInterrupt:
pass
解决方案
使用上下文管理器:
with open('6am-630am.mp3', 'wb') as f:
try:
with requests.get(stream_url, stream=True) as r:
while int(time.strftime('%M')) < 30: #do this till it's 6:30
for block in r.iter_content(1024):
f.write(block)
except KeyboardInterrupt:
pass
推荐阅读
- android - 如何将 Android Studio 项目迁移到基于 Android.mk 的项目,以作为 AOSP 构建的一部分构建?
- azure - 用于 VM 关机/开机通知的 Azure Logicapps
- python - yalm.dump python中的特殊字符
- entity-framework - 如何在具有多对多关系的 Entity Framework Core 5 Web API 中使用 HttpPost
- python - 检查图像是否透明
- django - Django中的页面范围变量
- c++ - 在源文件中声明函数模板时是否应该防止 ODR 违规?
- c# - 在 TextBox 控件的选择周围插入文本
- python - 无需任何外部库的 Python 图像裁剪
- python - Opencv轮廓区域返回错误结果