如何使用 python 中的 urllib 接收用户想要检索的文件的大小

How to receive the size of the file that the user wants to retrieve using urllib in python

我基本上是 python 的新手,我正在 python 使用 tkinter 和 urllib.request 构建这个下载程序,它是大功告成,但作为最后一步,我想添加一个进度条来显示文件的下载量。我发现我可以使用 TQDM 添加进度条,但首先我应该得到用户想要下载的文件的大小以显示程序下载了多少,然后我什么都没找到!谁能帮我吗? 我的代码(顺便说一句,如果您知道如何改进我的代码,我将不胜感激):

from tkinter import *
from tkinter import font as tkFont
import random
import urllib.request


def printsth():
    print("Yay it works! ")


def main_menu():
    root = Tk()
    # the top menu
    num = IntVar()
    var = IntVar()
    menu = Menu(root)
    root.config(menu=menu)
    submenu = Menu(menu)
    menu.add_cascade(label="File", menu=submenu)
    submenu.add_command(label="New project...", command=printsth)
    submenu.add_command(label="New ", command=printsth)
    submenu.add_separator()
    submenu.add_command(label="Exit", command=root.destroy)

    # the edit menu
    editmenu = Menu(menu)
    menu.add_cascade(label="Edit", menu=editmenu)
    editmenu.add_command(label="Redo...", command=printsth)

    # the tool bar
    toolbar = Frame(root, bg="light gray")
    insert_button = Button(toolbar, text="Insert an image", command=printsth)
    insert_button.pack(side=LEFT, padx=2, pady=2)
    print_button = Button(toolbar, text="Print", command=printsth)
    print_button.pack(side=LEFT, padx=2, pady=2)
    toolbar.pack(side=TOP, fill=X)

    # the status bar
    status_bar = Label(root, text="This is only an example...", bd=1, relief=SUNKEN, anchor=W)
    status_bar.pack(side=BOTTOM, fill=X)

    # the download frame
    def download_image():
        global formatname
        if num.get() == 1:
            name = random.randrange(1, 10000)
        else:
            name = str(name_entry.get())
        formatname = str(format_entry.get())
        '''if var.get() == 1:
            operator = str(url_entry.get())
            formatname = '.' + operator[-3] + operator[-2] + operator[-1]
        else:
            pass'''
        fullname = str(name) + formatname
        url = str(url_entry.get())
        urllib.request.urlretrieve(url, fullname)
    body_frame = Frame(root, bg="light blue")
    download_button = Button(body_frame, text="Download! ", command=download_image, border=3, width=20, height=5)
    download_design = tkFont.Font(size=12, slant='italic')
    download_button['font'] = download_design
    download_button.pack(side=LEFT, pady=5, padx=5)
    body_frame.pack(side=LEFT, fill=Y)
    # the main interaction menu
    inter_frame = Frame(root)
    url_entry = Entry(inter_frame)
    label = Label(inter_frame, text="Enter the image URL: ")
    file_format = Label(inter_frame, text="Choose your file format: ")
    format_entry = Entry(inter_frame)
    file_name = Label(inter_frame, text="File's name: ")
    name_entry = Entry(inter_frame)
    check_name = Checkbutton(inter_frame, text="Give a random name", variable=num)
    check_format = Checkbutton(inter_frame, text="Download with default format", variable=var)
    file_name.pack(anchor=CENTER, expand=1)
    name_entry.pack(anchor=CENTER, expand=1)
    check_name.pack(anchor=CENTER, expand=1)
    label.pack(anchor=CENTER, expand=1)
    url_entry.pack(anchor=CENTER, expand=1)
    file_format.pack(anchor=CENTER, expand=1)
    format_entry.pack(anchor=CENTER, expand=1)
    # check_format.pack(anchor=CENTER)
    inter_frame.pack(expand=1)
    root.mainloop()

    # the end!
main_menu()

要获得尺寸,请执行 HEAD 请求:

file_size = int(requests.head('https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tar.gz', headers={'accept-encoding': ''}).headers['Content-Length'])

或一个GET请求(可能不正确):

file size = int(requests.get('https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tar.gz').headers['Content-Length'])