Ensuring continuously updated image file is safe to open
Question: So here's the situation: I've got two Python programs, one to control a uEye
camera module, making use of the SimpleCV library, and another to do a bit of
analysis on the image. The reason for them being separate is that SimpleCV is
2.7, while a few modules I need to use in the analysis stage are for 3.X only.

The camera program will continuously capture and save an image to a location
(rewriting the old image), which I've timed to be around every 30 ms. The
analysis program takes in an image every 100 ms or so. Now, the issue I'm
concerned with is that if the analysis program tries to read in the image
while the camera program happens to be writing it, it will spring an error.

I'm fairly certain placing an exception statement to catch the OSError and
have it simply try again would suffice, but I feel that is a bit forceful.
I've also thought about having the camera program write a number (say, 100) of
images, to lesson the odds that the two will happen to be working on the same
file at once, but that seems unreliable. In a perfect world, I could ditch
SimpleCV and go with a 3.X module, allowing the writing and reading to happen
in sequence only, but I've yet to find a suitable replacement that works with
the camera.

Any thoughts on the most efficient, robust way of avoiding this issue?

Here is the (simplified) camera program:

    
    
    from SimpleCV import *
    
    cam = Camera(0)
    while True:
        img = cam.getImage()
        img.save("nav.jpg")
    

And the important part of the analysis program:

    
    
    from PIL import Image
    
    img = Image.open("nav.jpg")
    


Answer: The easiest way is to open the file with exclusive access so no-one can have
it open for the duration of you working with it. See [What is the best way to
open a file for exclusive access in
Python?](http://stackoverflow.com/questions/186202/what-is-the-best-way-to-
open-a-file-for-exclusive-access-in-python) for implementation details.

Be sure to `file.close()` or `with <file_open> as f` to close the file as soon
as you can to minimize interference with the agents that "continuously update"
it. Yes, and be sure to handle the file locked case in those agents.

