【问题标题】:Python: Unpredictable memory error when downloading large filesPython:下载大文件时出现不可预测的内存错误
【发布时间】:2011-03-30 21:40:40
【问题描述】:

我编写了一个 python 脚本,用于从 HTTP 服务器下载大量视频文件(每个 50-400 MB)。到目前为止,它在长长的下载列表中运行良好,但由于某种原因,它很少出现内存错误。

这台机器有大约 1 GB 的可用 RAM,但我认为在运行此脚本时它的 RAM 从未用完。

我已经在任务管理器和 perfmon 中监控了内存使用情况,它的行为与我所看到的一样:在下载过程中缓慢增加,然后在完成下载后恢复正常水平(没有小泄漏爬起来或类似的东西)。

下载行为的方式是创建文件,该文件保持在 0 KB 直到下载完成(或程序崩溃),然后它立即写入整个文件并关闭它。

for i in range(len(urls)):
    if os.path.exists(folderName + '/' + filenames[i] + '.mov'):
        print 'File exists, continuing.'
        continue

    # Request the download page
    req = urllib2.Request(urls[i], headers = headers)

    sock = urllib2.urlopen(req)
    responseHeaders = sock.headers
    body = sock.read()
    sock.close()

    # Search the page for the download URL
    tmp = body.find('/getfile/')
    downloadSuffix = body[tmp:body.find('"', tmp)]
    downloadUrl = domain + downloadSuffix

    req = urllib2.Request(downloadUrl, headers = headers)

    print '%s Downloading %s, file %i of %i'
        % (time.ctime(), filenames[i], i+1, len(urls))

    f = urllib2.urlopen(req)

    # Open our local file for writing, 'b' for binary file mode
    video_file = open(foldername + '/' + filenames[i] + '.mov', 'wb')

    # Write the downloaded data to the local file
    video_file.write(f.read()) ##### MemoryError: out of memory #####
    video_file.close()

    print '%s Download complete!' % (time.ctime())

    # Free up memory, in hopes of preventing memory errors
    del f
    del video_file

这是堆栈跟踪:

  File "downloadVideos.py", line 159, in <module>
    main()
  File "downloadVideos.py", line 136, in main
    video_file.write(f.read())
  File "c:\python27\lib\socket.py", line 358, in read
    buf.write(data)
MemoryError: out of memory

【问题讨论】:

    标签: python download out-of-memory


    【解决方案1】:

    您的问题在这里:f.read()。该行尝试将整个文件下载到内存中。取而代之的是,读取块 (chunk = f.read(4096)),并将这些块保存到临时文件中。

    【讨论】:

    • 如何知道下载完成?还是整体数据的长度?文档没有关于 f.read() 返回的对象的任何信息。
    • 您需要查看Content-length 标头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 2021-04-23
    • 2020-04-13
    • 2023-02-17
    • 2018-10-13
    • 1970-01-01
    相关资源
    最近更新 更多