如何在Python命令行URL下载器中添加进度条?
我用 Python 制作了一个简单的命令行 URL 下载器。当用户提供 URL 时,它会从 Web 读取文件并将其保存在字符串中,然后将该字符串保存在计算机上的文件中。
我想添加一个进度条。我该怎么办?
I have made a simple command-line URL downloader in Python. When the user supplies a URL it reads the file from web and saves it in a string, then saves the string in a file on the computer.
I want to add a progress bar. How should I go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是命令行上进度条的非常基本实现:
如果您希望它静态显示(即不是为进度条的每次更新输出新行,而是覆盖同一行)并结束)您应该将其包装到一些 curses 处理中。
This is a very basic implementation of a progress bar on the command line:
If you wanted it to appear statically (i.e. instead of outputting a new line for each update of the bar, to overwrite the same line over and over) you should wrap this into some curses handling.
计算出您正在下载的文件的总大小。这通常出现在 HTTP 标头
Content-Length
(以字节为单位)中。统计迄今为止下载的总数据量。
任何时刻应填充的进度条数量由以下公式给出:
(到目前为止已下载)/(总大小)
,它是 0 到 1 之间的数字(含 0 和 1)。Figure out the total size of the file you're downloading. This is often present in the HTTP header
Content-Length
(which is in bytes).Keep count of the total data downloaded so far.
The amount of the progress bar that should be filled at any moment is given by the formula:
(downloaded so far) / (total size)
which is a number between 0 and 1, inclusive.