簡體   English   中英

Python:下載大文件時出現不可預知的內存錯誤

[英]Python: Unpredictable memory error when downloading large files

我寫了一個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

你的問題在這里: f.read() 該行嘗試將整個文件下載到內存中。 而不是那樣,讀取塊( chunk = f.read(4096) ),並將碎片保存到臨時文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM