Python 3 和带有进度条的请求

标签 python python-3.x request progress-bar chunks

我正在尝试使用 python 请求下载文件。它适用于 python 2.7,但现在不行。我真的很困惑,必须有一个更简单的答案。由于文件可能非常大,我真的想要一个进度条,我正在使用 python progressbar 来完成这项工作。

                r = requests.get(file_url, data={'track': 'requests'})
                size = int(r.headers['Content-Length'].strip())
                self.bytes = 0
                widgets = [name, ": ", Bar(marker="|", left="[", right=" "),
                    Percentage(), " ",  FileTransferSpeed(), "] ",
                    self,
                    " of {0}MB".format(round(size / 1024 / 1024, 2))]
                pbar = ProgressBar(widgets=widgets, maxval=size)
                pbar.start()

                file = b""
                for chunk in r.iter_content()
                    if chunk:
                        file += chunk

                        self.bytes += 1
                        pbar.update(self.bytes)

我发现使用 iter_content 是获得持续更新的最佳方式。我确实尝试过 iter_lines 但它弄乱了文件。它突然停止下载并且真的很慢,下载 10% 需要 15 分钟,然后停止。并尝试以字节模式打开文件并写入它不起作用,它根本不会抛出错误。当我尝试使用

打印 block 包含的内容时
print(chunk.decode("utf-8")

有效,但只有几个字符。在某些时候它提示

UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

即使在 iter_content 中使用“decode_unicode=True”也无济于事。我很难过,不知道该怎么办。使用 Py3k 应该不难。

最佳答案

设法修复它。所以这是更新后的代码:

r = requests.get(file_url)
size = int(r.headers['Content-Length'].strip())
self.bytes = 0
widgets = [name, ": ", Bar(marker="|", left="[", right=" "),
    Percentage(), " ",  FileTransferSpeed(), "] ",
    self,
    " of {0}MB".format(str(round(size / 1024 / 1024, 2))[:4])]
pbar = ProgressBar(widgets=widgets, maxval=size).start()
file = []
for buf in r.iter_content(1024):
    if buf:
        file.append(buf)
        self.bytes += len(buf)
        pbar.update(self.bytes)
pbar.finish()

下载速度从 7kb/s 变为 400+ kb/s。它正在全面运作。

关于Python 3 和带有进度条的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10525635/

相关文章:

python - 如何在python中使用beautifulsoup获取完整的href链接

python - 在python中反转链表

python - 使用自定义函数迭代 Pandas 中系列中的每个项目

python-3.x - Python 3 创建 md5 哈希

python - 定期更新带有标签的 ProgressBar

node.js - 如何在 Node.js 中发出路径中带有反斜杠的请求?

python - 缩放时如何调整容器/像素的大小

Windows 中的 Python 套接字问题 : socket. MSG_DONTWAIT

python - 如何使用lxml和python查找特定标签中的文本?

node.js - 错误: Body attribute missing in multipart while using googleapis node module