是否可以在 urlretrive 的另一个文件中使用钩子?

时间:2021-02-15 13:06:32

标签: python python-3.x urllib

我正在使用 urlretrive 在 Python 中创建文件下载器。 我想在主文件中做一个进度条,但是负责下载的函数在另一个文件中。

main.py:

from download import dl

def bar(count, block_size, total_size):
    print(count)
    print(block_size)
    print(total_size)

dl("https://google.com/index.html")

下载.py:

import urllib
from urllib.parse import urlsplit
from urllib.request import urlretrieve, urlopen


def dl(url,path=None):
    name = urlsplit(url).path.split("/")[-1]
    urlretrieve(url, name, reporthook = bar)

我希望 dl 函数在主文件中使用 reporthook。当然,我得到了一个错误。

NameError: name 'bar' is not defined

有没有办法做到这一点,或者我必须把这个函数放在主文件中?

1 个答案:

答案 0 :(得分:0)

def dl(url, bar, path=None):
    name = urlsplit(url).path.split("/")[-1]
    urlretrieve(url, name, reporthook = bar)

dl("https://google.com/index.html", bar)

工作。

import download

...

if __name__ == '__main__':
    download.dl("https://google.com/index.html")

...
import main

def dl(url, path=None):
    name = urlsplit(url).path.split("/")[-1]
    urlretrieve(url, name, reporthook = main.bar)

也有效。

相关问题