File locking (Re: How do I force a single instance of a python app?)

Richard van de Stadt stadt at cs.utwente.nl
Thu Oct 26 17:31:30 EDT 2000


Donn Cave wrote:
> 
> Quoth Dale Strickland-Clark <dale at out-think.NOSPAMco.uk>:
> | "Joshua Muskovitz" <josh at open.com> wrote:
> |>"Dale Strickland-Clark" <dale at out-think.NOSPAMco.uk> wrote in message
> |>news:urodvssp7e7cmbv1ljlqnqgej9rjhfqbli at 4ax.com...
> |>> Open a flag file exclusively for writing. If successful you are alone,
> |>> if not, another instance already has the file.
> |>>
> |>> The OS should close the file and free the exclusive lock if the app
> |>> crashes.
> |>
> |> This would be great, but on my Win2k box, I can open up the same file for
> |> write in two separate Python instances at the same time.  :-(
> |>
> |> The second instance of open("foo","w") does not fail.
> |
> | This is pretty naf, isn't it. I get the same.
> |
> | I can even open for append from two different instances of the same
> | program and get interleaved output.

Of course. This is another issue than the original question (see my
other posting in this thread for my solution), but if you want an
application to have exclusive rights to write to a file, you need
to lock the file after opening it:

f = open ('somefile', 'w')
f.lock('w|')
f.write ('stuff')
f.lock('u')
f.close()

Still, this only works if all programs that want to write 'somefile' use this.

This also works in case the program wants to write to a file which is located
on a remote system, and which is down. The program waits until the remote system
is up again.

> | Does this occur with other languages/libraries?  I haven't tested it
> | but I can't help wondering if Python is using inappropriate options
> | when opening output files.

It is not inappropriate. What if you _want_ or don't care about interleaved
output? You're just confused about the defaults :-)

> Normal, correct results for C library stdio, which is the basis for
> the Python file object.
> 
>         Donn Cave, donn at u.washington.edu

Richard.



More information about the Python-list mailing list