如何使用进度条在Python中复制文件? [英] How to copy a file in Python with a progress bar?
问题描述
使用 shutil.copy()
复制大文件时,不会显示操作的进展情况。
我已经把一些有用的东西放在一起 - 它使用一个简单的ProgressBar类(它简单地返回一个简单的ASCII进度条,作为一个字符串)和一个 open()。read()
和 .write()
来做实际的复制。它使用 sys.stdout.write(\r%s \r%(the_progress_bar))
显示进度条,这有点冒险,但它工作。
您可以看到代码(在上下文中)在github这里
有没有内置的模块可以做得更好?这个代码有什么改进吗?
有两件事:
- 我会使默认块大小大于512.我将从16384开始,也许更多。
- 对于模块化来说,最好是让
copy_with_prog
函数不输出进度条本身,而是调用一个回调函数,这样调用者可以决定如何显示进度。
也许是这样的:
def copy_with_prog(src,dest,callback = None):
while:
#copy loop stuff
if callback:
callback(pos,total)
prog = ProgressBar(...)
copy_with_prog(src,dest,lambda pos,total:prog.update(pos,total))
When copying large files using shutil.copy()
, you get no indication of how the operation is progressing..
I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of open().read()
and .write()
to do the actual copying. It displays the progress bar using sys.stdout.write("\r%s\r" % (the_progress_bar))
which is a little hackish, but it works.
You can see the code (in context) on github here
Is there any built-in module that will do this better? Is there any improvements that can be made to this code?
Two things:
- I would make the default block size a lot larger than 512. I would start with 16384 and perhaps more.
- For modularity, it might be better to have the
copy_with_prog
function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress.
Perhaps something like this:
def copy_with_prog(src, dest, callback = None):
while True:
# copy loop stuff
if callback:
callback(pos, total)
prog = ProgressBar(...)
copy_with_prog(src, dest, lambda pos, total: prog.update(pos, total))
这篇关于如何使用进度条在Python中复制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!