If you have a situation where multiple programs could be writing to the same file at the same time, file locking it is a simple way to keep things safe and coordinated. I’ve found the portalocker code/module to be the best way to achieve this in Windows. Below is some sample code for using this module, but be sure to notice the trick in line 5, or you’ll be moderately confused for three months and think the code is working when it’s not (more on that after the sample.).
Sample Usage:
import portalocker
#access the file you want to lock
token=file('token.txt','r+') #use r+ for some reason ...
#Lock the file
portalocker.lock(token,portalocker.LOCK_EX|portalocker.LOCK_NB)
#Brag about it, or perhaps use the file ...
print 'I have this file! No one can use it!'
time.sleep(10)
#Relinquish
token.close()
print 'Ok, you can use it now'
Notice that weird looking “portalocker.LOCK_EX|portalocker.LOCK_NB” on line 5? That’s what made it work for me. I don’t know how or why but finally got this idea from a google code search on portalocker.
If anyone knows why “portalocker.LOCK_EX|portalocker.LOCK_NB” works while only “LOCK_EX” works but just makes other programs hang at opening token.txt, and “LOCK_NB” and “LOCK_SH” don’t work at all, then you’ll get a $5 dollar gift card for Answer My Searches (assuming I ever sold merchandise on this site which I can’t fathom, oh and it expires in 6 months! .. but I’d still appreciate the answer
Update:
Jody, from Gaithersburg, Maryland writes in that LOCK_EX is for blocking access and LOCK_EX|portalocker.LOCK_NB is for not blocking which I suppose means causing another program to raise an error when accessing a locked file as shown in this link. Enjoy the gift card, Jody!
[tags]portalocker, lock files, lock, flock, LOCK_NB, LOCK_SH, LOCK_EX[/tags]