我正在使用 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
有没有办法做到这一点,或者我必须把这个函数放在主文件中?
答案 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)
也有效。