bug with os.rename in 2.4.1?

Nick Craig-Wood nick at craig-wood.com
Tue Apr 28 21:30:02 CEST 2009


t123 <tom.lukes at gmail.com> wrote:
>  It's running on solaris 9.  Here is some of the code.  It's actually
>  at the beginning of the job.  The files are ftp'd over.  The first
>  thing that happens is that the files get renamed before any processing
>  of the file.  And when it fails, it always fails at the first file,
>  comm.dat.  What I can't understand is why the inconsistent behavior.
> 
>  try:
>          if os.path.exists(paths.xferin_dir+'/COMM.DAT'):
>            os.rename(paths.xferin_dir+'/COMM.DAT',paths.xferin_dir+'/

This code is inherently racy... What if two copies of your code
started simultaneously?  They might both run the os.path.exists but
only one will succeed in the os.rename.

You could write instead

    try:
        os.rename(paths.xferin_dir+'/COMM.DAT',paths.xferin_dir+'/COMM.DAT'+'.0')
    except OSError:
        pass

Which isn't racy.  Or if you wanted to be more thorough

    import errno
    try:
        os.rename(paths.xferin_dir+'/COMM.DAT',paths.xferin_dir+'/COMM.DAT'+'.0')
    except OSError, e:
        if e.errno != errno.ENOENT:
            raise

The traceback should show the exact problem though.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list