【问题标题】:Stuck in while loop when writing to file写入文件时卡在while循环中
【发布时间】:2013-07-13 21:20:54
【问题描述】:

我的代码是:

f=file('python3.mp3','wb')
conn=urllib2.urlopen(stream_url)
while True:
    f.write(conn.read(1024))

其中 stream_url 是我以 mp3 格式 (python3.mp3) 保存到磁盘的流的 url。

文件成功保存,但 while 循环永远不会终止。我想我对“真实”条件代表什么感到有些困惑?是在播放流的时候吗?连接打开时?我尝试在 while 循环中添加 conn.close() 和 f.close() ,但这会引发错误,因为它似乎正在中断写入过程。

【问题讨论】:

    标签: python-2.7 io while-loop


    【解决方案1】:

    while True 永远循环,或者直到你 break。当您阅读整个流时,您需要break,如下所示:

    f = file('python3.mp3','wb')
    conn = urllib2.urlopen(stream_url)
    while True:
        packet = conn.read(1024)
        if not packet:
            break  # We've read the whole thing
        f.write(packet)
    

    【讨论】:

      【解决方案2】:

      只要条件为Truewhile 循环就会在其主体中运行代码。你的条件总是True,所以你的while 循环永远不会结束,这是正确的。 while 循环不关心除了它的条件之外的任何东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-05
        • 2021-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多