每小时X分钟后中断请求流

时间:2019-03-21 00:14:55

标签: python while-loop python-requests

抱歉,这里有菜鸟问题。我正在尝试从早上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

1 个答案:

答案 0 :(得分:0)

使用上下文管理器:

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