correct way to catch exception with Python 'with' statement

Steve D'Aprano steve+python at pearwood.info
Fri Dec 2 00:41:17 EST 2016


On Fri, 2 Dec 2016 11:26 am, DFS wrote:

>> For most programs, yes, it probably will never be a problem to check
>> for existence, and then assume that the file still exists.  But put that
>> code on a server, and run it a couple of million times, with dozens of
>> other processes also manipulating files, and you will see failures.
> 
> 
> If it's easy for you, can you write some short python code to simulate
> that?

Run these scripts simultaneously inside the same directory, and you will see
a continual stream of error messages:

# -- a.py -- 
filename = 'data'
import os, time

def run():
    if os.path.exists(filename):
        with open(filename):
            pass
    else:
        print('file is missing!')
        # re-create it
        with open(filename, 'w'):
            pass

while True:
    try:
        run()
    except IOError:
        pass
    time.sleep(0.05)



# -- b.py --
filename = 'data'
import os, time

while True:
    try:
        os.remove(filename)
    except OSError:
        pass
    time.sleep(0.05)




The time.sleep() calls are just to slow them down slightly. You can leave
them out if you like.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list