[python-win32] Re: Help: using msvcrt for file locking

Sheila King sheila@thinkspot.net
Sun, 26 Aug 2001 18:43:52 -0700


On Mon, 27 Aug 2001 08:09:01 +1000, Mark Hammond <MarkH@ActiveState.com>  wrote about [python-win32]
Re: Help: using msvcrt for file locking:

:Try using LockFile - the MSDN documentation implies that it is supported 
:on all Win32 platforms, and the error you get:
:
:pywintypes.api_error: (120, 'LockFileEx', 'This function is only valid
:in Win32 mode.')
:
:implies you are running on Win9x.

Yes, I am running on Win98.

:A quick look at portalocker implies you will also want to drop all 
:references to "_overlapped" - replace them with "None".

I tried that. Unfortunately, "None" didn't work. It gave me an error 
message asking for an integer.

I spent a bit of time trying a few different things, and looking at the msdn site (here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/hh/winbase/filesio_8l6b.asp

and eventually I came up with this code:

filename = r'e:\apache\cgi-bin\pylinks\datalog.txt'

import win32con
import win32file
import pywintypes
from time import strftime, localtime, time

f = open(filename, 'a+')
fd = win32file._get_osfhandle(f.fileno())
win32file.LockFile(fd, win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, 0xffff0000,0)
timestamp = strftime("%m/%d/%Y %H:%M:%S\n", localtime(time()))
f.write(timestamp)
win32file.UnlockFile(fd, 0, 0, 0xffff0000,0)
f.close()

And the only error I'm getting now is:

Traceback (most recent call last):
  File "E:\programs\LearningPython\fileIO\win32LockFile.py", line 13, in ?
    win32file.UnlockFile(fd, 0, 0, 0xffff0000,0)
pywintypes.api_error: (33, 'UnlockFile', 'The process cannot access the file because\r\nanother
process has locked a portion of the file.')


Which is a big improvement over what I was getting before.

Unfortunately, I'm just taking blind stabs in the dark. I'm in over my 
head, and I don't really know what I'm doing.

Would getting the Programming Python on Win32 help me learn this Windows 
API stuff. Or would I have to get a separate book on Windows API and then 
get the Programming Python on Win32 to help me translate that knowledge into Python?

(I have to say, that the msdn documentation is sketchy at best, and I have 
to do a lot of guesswork. I looked at some of the source files in the win32 
directories, but it didn't help a whole lot.)

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/