I want to open a file which is periodically written to by another application. This application cannot be modified. I\'d therefore like to only open the file when I know it
One thing I've done is have python very temporarily rename the file. If we're able to rename it, then no other process is using it. I only tested this on Windows.
Will your python script desire to open the file for writing or for reading? Is the legacy application opening and closing the file between writes, or does it keep it open?
It is extremely important that we understand what the legacy application is doing, and what your python script is attempting to achieve.
This area of functionality is highly OS-dependent, and the fact that you have no control over the legacy application only makes things harder unfortunately. Whether there is a pythonic or non-pythonic way of doing this will probably be the least of your concerns - the hard question will be whether what you are trying to achieve will be possible at all.
UPDATE
OK, so knowing (from your comment) that:
the legacy application is opening and closing the file every X minutes, but I do not want to assume that at t = t_0 + n*X + eps it already closed the file.
then the problem's parameters are changed. It can actually be done in an OS-independent way given a few assumptions, or as a combination of OS-dependent and OS-independent techniques. :)
T
seconds (e.g. opens the file, performs one write, then closes the file), and re-opens it more or less every X
seconds, where X
is larger than 2*T
.
stat
the filenow()
, yielding D
T
<= D
< X
then open the file and do what you need with itT
/X
decreases. On *nix you may have to double check /etc/ntpd.conf
for proper time-stepping vs. slew configuration (see tinker). For Windows see MSDNlsof
)
lsof
or, on some systems, simply check which file the symbolic link /proc/<pid>/fd/<fdes>
points to
UPDATE 2
If favouring the "check whether the legacy application has the file open" (intrusive approach prone to race conditions) then you can solve the said race condition by:
lsof
or ProcessExplorer
)Unix does not have file locking as a default. The best suggestion I have for a Unix environment would be to look at the sources for the lsof command. It has deep knowledge about which process have which files open. You could use that as the basis of your solution. Here are the Ubuntu sources for lsof.