Synchronous shutil.copyfile()

Jean-Paul Calderone exarkun at divmod.com
Tue Jan 30 10:59:30 EST 2007


On Tue, 30 Jan 2007 15:05:23 +0000, Hugo Ferreira <bytter at gmail.com> wrote:
>Hi there,
>
>I have a problem. I'm using calling shutil.copyfile() followed by
>open(). The thing is that most of the times open() is called before
>the actual file is copied. I don't have this problem when doing a
>step-by-step debug, since I give enough time for the OS to copy the
>file, but at run-time, it throws an exception.
>
>Is there anyway to force a sync copy of the file (make python wait for
>the completion)?

shutil.copyfile() _is_ synchronous.  Check out the source:

def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)

def copyfile(src, dst):
    """Copy data from src to dst"""
    if _samefile(src, dst):
        raise Error, "`%s` and `%s` are the same file" % (src, dst)

    fsrc = None
    fdst = None
    try:
        fsrc = open(src, 'rb')
        fdst = open(dst, 'wb')
        copyfileobj(fsrc, fdst)
    finally:
        if fdst:
            fdst.close()
        if fsrc:
            fsrc.close()

The problem you are experiencing must have a different cause.

Jean-Paul



More information about the Python-list mailing list