tags:

views:

77

answers:

2

I've got a little script for sorting out my dowloaded files and it works great, but I'd like to print out the progress of a file move, for when it's doing the big ones, right now I do something like:

print "moving..."
os.renames(pathTofile, newName)
print "done"

But I'd like to be able to see something like a progress bar ( [..... ] style) or a percentage printed to stdout.

I don't need/want a gui of any sort, just the simplest / least-work ( :) ) way to get the operation progress).

Thanks!

A: 

You won't be able to get that kind of information using os.renames. Your best bet is to replace that with a home grown file copy operation but call stat on the file beforehand in order to get the complete size so you can track how far through you are.

Something like this:

source_size = os.stat(SOURCE_FILENAME).st_size
copied = 0
source = open(SOURCE_FILENAME, 'rb')
target = open(TARGET_FILENAME, 'wb')

while True:
    chunk = source.read(32768)
    if not chunk:
        break
    target.write(chunk)
    copied += len(chunk)
    print '\r%02d%%' % (copied * 100 / source_size),

source.close()
target.close()

Note however that this will more than likely be markedly slower than using os.rename.

Benno
A: 

There isn't any way to get a progress bar because the "rename" call that moves the file is a single OS call.

It's worth noting that the "rename" call only takes time if the source and destination are on different physical volumes. If they're on the same volume, then the rename will take almost no time. If you know that you're copying data between volumes, you may wish to use functions from the shutil module such as copyfileobj. There is no callback for progress monitoring, however you can implement your own source or destination file-like object to track progress.

Greg Hewgill