List Info

Thread: File locking




File locking
country flaguser name
United States
2007-03-12 13:04:51
I'm always disappointed when I find something that Python doesn't handle in a platform independent way.  It seems to me that file locking is in that boat.
 
1. I don't see a way to atomically open a file for writing if and only if it doesn't exist without resorting to os.open and specialized platform O_XXX flags.
 
2. I don't see a way to atomically open a file for writing and obtain a lock on the file.
 
3. I don't see a platform independent way to obtain a lock on a file. ; You have to do something goofy like
if sys.platform == win32:
    import msvcrt
else:
    import fcntl
and then similar things to call the correct functions with the correct flags.
 
Please let me know if I'm missing something since they seem like normal file operations that I would hope Python would abstract away.  If not, are there any PEPs concerning this for Python3K?
 
Thanks,
Jeff
Re: File locking
country flaguser name
United Kingdom
2007-03-21 18:28:41
Jeff,

Just catching up after a week on vacation, but nobody
seems to have picked this up so...

> I'm always disappointed when I find something that
Python
> doesn't handle in a platform independent way.

That's often because the platforms all do it too
differently! 

> 1. I don't see a way to atomically open a file for
writing if and 
> only
> if it doesn't exist

Doesn't the os.path.exists() function work on all
platforms?

> 2. I don't see a way to atomically open a file for
writing and 
> obtain a
> lock on the file.

That's usually automatic on filesystems that support it.
(And
impossible on those that don't! - eg DOS/FAT)

> 3. I don't see a platform independent way to obtain a
lock
> on a file.

Not all platforms support file locking. And some platforms
(eg. Windows) only support it on some filesystems
(FAT32 up)

> You have to do something goofy like
> if sys.platform == win32:
>    import msvcrt
> else:
>     import fcntl
> and then similar things to call the correct functions
with the
> correct flags.

You only have to do this on the rare occasions when you
want
to lock a file and you are not writing to it. Otherwise the
act of
writing should reate a lock, if possible. (Or so I, perhaps
niaively,
believe!)

> Please let me know if I'm missing something

Maybe os.path.exists() and maybe automatic locking on
writes.

HTH, and if not elicits other replies!


-- 
Alan Gauld
Author of the Learn to Program web site
http://ww
w.freenetpages.co.uk/hp/alan.gauld 


_______________________________________________
Tutor maillist  -  Tutorpython.org
http://
mail.python.org/mailman/listinfo/tutor

[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )