How can one open a file for exclusive access?

Parzival Herzog parz at shaw.SpamBucket.ca
Mon Jan 14 16:13:20 EST 2002


O.K. So I started an argument!
I found that the following code appears to work (Win2k)

import win32file
import msvcrt, os, sys

handle = win32file.CreateFile("SHARE.txt",
    win32file.GENERIC_WRITE,
    0, # i.e. "not shared" is the default
    None,
    win32file.OPEN_ALWAYS,
    win32file.FILE_ATTRIBUTE_NORMAL,
    None)

win32file.SetFilePointer(handle, 0, win32file.FILE_END)

fd = win32file._open_osfhandle(handle,os.O_TEXT)
f = os.fdopen(fd,"wa")
print >>f, sys.argv
raw_input("please type return")
f.close()

This took some experimentation!
I found errors in the win32file.._open_osfhandle documentation;
without the "wa" argument to os.fdopen, the print statement below
it raises the (very misleading) exception:
IOError: [Errno 2] No such file or directory

Now, it seems that non-shared file access is the Win32 default,
so can anyone explain why the Python "open", (which presumably
is based on the C library "open", which on Win32 is based on
"CreateFile", which defaults to non-shared access, ) gives me
unrestricted shared access? Who would want such a thing by
default?

The argument between Alex and Syver suggests that in some or
is it all Unices, unrestricted shared access is the norm. Is that so?

It would seem that writing a robust portable program (i.e. it can
survive running a second instance of itself) for a simple
matter such as updating a file would be VERY difficult in Python.

BTW, if I were to use the file-locking  recipie Alex suggests,
then is it true (under Windows) that if the lock is not explicitly
released by the locking application, that it persists after the
application terminates?

- Parzival

"Syver Enstad" <syver-en+usenet at online.no> wrote in message
news:upu4cvkdw.fsf at online.no...
> "Alex Martelli" <aleax at aleax.it> writes:
> > > I want to be able to open a file for writing exclusively,
> > > that while it is open, no other process may read or
> > > write to that file.
> >     ...
> > > So, how, in Python, can one open a file for exclusive
> > > access?
> >
> > A good example of such file-locking, cross-platform, is at:
> >
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203
> >
>
> Hmm... I might be mistaken here Alex, but as far as I can remember
> this is advisory file locking, where one is using a file as a kind of
> synchronization primitive, access to the file is not really affected
> at all. So it doesn't solve the problem the poster was addressing;
> which was that he didn't want any external program to be able to write
> to his file while he had it open. To solve that the only solution I
> know of is to use the win32file functions that allows you to specify
> this, ie win32file.CreateFile and so on.
>
> --
>
> Vennlig hilsen
>
> Syver Enstad





More information about the Python-list mailing list