首页 > 解决方案 > 在一小时后 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

标签: pythonwhile-looppython-requests

解决方案


使用上下文管理器:

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

推荐阅读