[python-win32] pure python way to open a file with write deny for others

Preston Landers planders at gmail.com
Fri Mar 6 16:04:14 EST 2020


Is advisory file locking an option? Such as the "portalocker" module for Python?

You can have your writer process obtain an exclusive lock (and block
until it's obtained), while the readers obtain shared locks for the
duration of their read.

Readers don't block other readers, while writers block both writers and readers.

https://github.com/WoLpH/portalocker

On Fri, Mar 6, 2020 at 10:51 AM Robin Becker <robin at reportlab.com> wrote:
>
> On 05/03/2020 16:04, Eryk Sun wrote:
> > On 3/5/20, Robin Becker <robin at reportlab.com> wrote:
> >> I want to be able to read a windows file which is being periodically written
> >> by another process.
> >
> > I'm having difficulty reconciling this sentence with the subject line.
>
> OK I want to read the (small) file completely. The other process may try to re-write the file while I am reading it. I
> thought that denying them write permission for the short time I have the file open for reading might make incomplete
> files less likely. So far the applications seem to be able to operate in this fashion and the small files seem to be
> complete.
>
> Of course the other process may adopt a completely orthogonal scheme of opening with a different name and then renaming,
> but I would then try to read the new version as its time stamp would change. We have no access to the internals of the
> writer and are just attempting to push textfile changes from a folder to a server. Perhaps there's a better way to do that.
>
>
> > If you want to open a file for reading that's already open for
> > writing, then the open has to share write access, not deny it (where
> > to "deny" access means to not share access) [1]. That's not an issue
> > since Python shares read and write access when opening a file. (Note
> > that the share mode applies to all opens. It is not related to
> > processes, so whether it's another process or the current process
> > that's writing to the file is irrelevant to the problem.)
> >
> > I wouldn't use FILE streams in Python 3. I'd pass an `opener` to
> > Python `open` that uses ctypes or PyWin32 to get a handle via
> > `CreateFileW`, and then msvcrt.open_osfhandle to wrap the handle with
> > a C file descriptor. The opener function signature is opener(filename,
> > flags) -> fd.
> >
> > [1]: https://docs.microsoft.com/en-us/windows/win32/fileio/creating-and-opening-files
> >
>
>
> --
> Robin Becker
> _______________________________________________
> python-win32 mailing list
> python-win32 at python.org
> https://mail.python.org/mailman/listinfo/python-win32


More information about the python-win32 mailing list