python - Opening already opened file does not raise exception -


consider 2 python programs:

script_a.py:

from datetime import datetime time import sleep  while true:     sleep(1)     open('foo.txt', 'w') f:         sleep(3)         s = str(datetime.now())         f.write(s)         sleep(3) 

script_b.py:

while true:     open('foo.txt') f:         s = f.read()         print s 

run script_a.py. while running, start script_b.py. both happily run, script_b.py outputs empty string if file opened script_a.py.

i expecting ioerror exception raised, telling me file opened, didn't happen, instead file looks empty. why , proper way check if opened process? ok check if empty string returned , try again until else read, or there more pythonic way?

see other answer , comments regarding how multiple file opens work in python. if you've read that, , still want lock access file on posix platform, can use fcntl library.

keep in mind that: a) other programs may ignore lock on file, b) networked file systems don't implement locking well, or @ c) sure careful release locks , avoid deadlock flock won't detect [1][2].

example.... script_a.py

from datetime import datetime time import sleep import fcntl  while true:     sleep(1)     open('foo.txt', 'w') f:         s = str(datetime.now())          print datetime.now(), "waiting lock"         fcntl.flock(f, fcntl.lock_ex)         print datetime.now(), "lock clear, writing"          sleep(3)         f.write(s)          print datetime.now(), "releasing lock"         fcntl.flock(f, fcntl.lock_un) 

script_b.py

import fcntl datetime import datetime  while true:     open('foo.txt') f:         print datetime.now(), "getting lock"         fcntl.flock(f, fcntl.lock_ex)         print datetime.now(), "got lock, reading file"          s = f.read()          print datetime.now(), "read file, releasing lock"         fcntl.flock(f, fcntl.lock_un)          print s 

hope helps!


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -