2017-05-07 1 views
3

urllib.request.urlretrieveを使用しているときに、ファイルサイズなどの情報と共に、コンソールにダウンロードされたダウンロードの状態を表示する方法があるのでしょうか?ダウンロードプロセスの表示方法を教えてください。

は、ここで私は上のテストしていたコードです:

#!/usr/bin/env python3.5.2 

import urllib.request 
import os 


# make sure to change the directory before you test the code 
directory = r'C:\Users\SalahGfx\Desktop\Downloads' 

url = 'https://upload.wikimedia.org/wikipedia/en/d/d8/C4D_Logo.png' 

def get_name_path(): 
    image_name = url.split('/')[-1] 
    return os.path.join(directory, image_name) 

urllib.request.urlretrieve(url, get_name_path()) 

print('The Image has been downloaded!') 

答えて

3

に建てられたものありませんあなたはそれを自分で記述する必要があります。幸いにも、それほど難しいことではありません。あなたはちょうどヘッダーからコンテンツの長さを読んで、そしてチャンクによって応答を読む必要があります。ここでは、コード

import urllib2, sys 

def chunk_report(bytes_so_far, chunk_size, total_size): 
    percent = float(bytes_so_far)/total_size 
    percent = round(percent*100, 2) 
    sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" % 
        (bytes_so_far, total_size, percent)) 

    if bytes_so_far >= total_size: 
     sys.stdout.write('\n') 

def chunk_read(response, chunk_size=8192, report_hook=None): 
    total_size = response.info().getheader('Content-Length').strip() 
    total_size = int(total_size) 
    bytes_so_far = 0 

    while 1: 
     chunk = response.read(chunk_size) 
     bytes_so_far += len(chunk) 

     if not chunk: 
      break 

     if report_hook: 
      report_hook(bytes_so_far, chunk_size, total_size) 

    return bytes_so_far 

def get_name_path(): 
    image_name = url.split('/')[-1] 
    return os.path.join(directory, image_name) 

# make sure to change the directory before you test the code 
directory = r'C:\Users\SalahGfx\Desktop\Downloads' 

url = 'https://upload.wikimedia.org/wikipedia/en/d/d8/C4D_Logo.png' 

response = urllib.request.urlopen(url, get_name_path()) 
chunk_read(response, report_hook=chunk_report) 

urllib2.request.retrievelegacyとみなされ、まもなく廃止されますので、それは私がurllib.request.urlopenを使用していることに注意することが重要ですです。

+0

お返事ありがとうございます。私は今、それを行うことの背後にある論理を理解していますが、私は、urlopenがファイル名なしでurlを取ることを知っていますので、urlretrieveを置き換える唯一の方法ですか? – SalahGfx

関連する問題