Can Python with TOCTOU statement?

Suppose it file.txt

closes or is removed during the delay between open

and write

. (or can he?)

Then this situation might arise TOCTOU ?

with

claim to be atomic until blocked or not?

with open("file.txt") as f :
    # ...delayed...
    f.write("something")

      

+3


source to share


1 answer


Could this happen?

Use case 1 : Python itself deletes the file *

yes it can happen. I just tested like this:

In [1]: with open("file.txt", "w") as f :
   ...:     f.write("Something Old")
   ...:

In [2]: !cat ./file.txt
Something Old
In [3]: import os
   ...: with open("file.txt","w") as f:
   ...:     os.remove("./file.txt")
   ...:     print f.write("Something new")
   ...:
None

In [4]: !cat ./file.txt
cat: ./file.txt: No such file or directory

      

Usage example 2: Also python deletes the file.



Then it was also found that the behavior is the same.

In [1]: !cat ./file.txt
Something Old
In [2]: import os
   ...: import time
   ...:
   ...: with open("file.txt","w") as f:
   ...:     time.sleep(15)
   ...:     print f.write("Something new")
   ...:
None

In [3]: !cat ./file.txt
cat: ./file.txt: No such file or directory

      

How to avoid it?

You can use exclusive locking fcntl.lockf ()

Edit: There is another caveat here. Locking a file may not be direct and may be OS dependent, how is the best way to open a file for exclusive access in Python?

+2


source







All Articles