2

I would like to implement a cooperative file locking mechanism in Python, that would also work on remote partitions (e.g. NFS), with a simple code (I want to avoid using a third-party module, because I want some specific open-source code to not have dependencies).

There are solutions out there that look relatively cross-platform, but they are more complicated than I would like: ideally the exact same lines of code would run on all platforms.

A solution is to use some atomic operation that tries to create a lock and fails if it cannot (e.g. a lock in the form of a directory). Creating a directory is atomic on Unix, so that's a good first step. Now, what would be an equivalent solution for Windows? I have read somewhere that maybe creating a link (how?) would be atomic; if creating a directory is atomic on Windows, that would be even better, as the same code could be used for both Windows and Unix, but I can't find out whether this is the case.

To summarize: what would be a simple, cross-platform Python code (no library) for creating (and releasing) a cooperative file lock, that also works on remote partitions? The directory creation route looks promising, but does it work on Windows?

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
  • 1
    Unrelated to the question, but to the comment, still think people should be forced to comment / pick a reason when downvoting, I know folks on meta disagree with it, but it's just annoying when you take time to ask a well-prepared question like that and get it downvoted... – Alexandre Beaudet May 07 '18 at 08:37
  • 1
    Agreed. Now, I a "close" flag (for a "too broad" question) was raised after my comment, so that may be the explanation for the downvote. :) – Eric O. Lebigot May 07 '18 at 08:39
  • Before going down the rabbit hole of seeking atomic file-system functions, are you aware of [`msvcrt.locking`](https://docs.python.org/3/library/msvcrt.html#msvcrt.locking) for Windows? – Eryk Sun May 07 '18 at 21:21
  • I am, thanks. But again, I would prefer using the same code for all platforms, so that rules out the Windows-specific `msvcrt` module. – Eric O. Lebigot May 08 '18 at 05:57

0 Answers0