PIL : wait for image.save()

Hi,
I’m looking for a way to have python execution waiting for image to save before doing next step.
How could I be sure the file is entirely saved before calling another function ?

Thanks

Here is what I’ve done :

        Screen = ImageGrab.grab(bbox)
        Screen.save(filePath)
        del Screen

        # check for file saved
        noinfinite = 0
        while True:
            time.sleep(0.2)
            if os.path.isfile(filePath):
                break
            if noinfinite > 25:
                break
            noinfinite += 1

It is better, but still not ok. Indeed, once the file is created it detect it, but this doesn’t means the file is fully written …
Any idea ?

I’m not sure why it wouldn’t be fully written. I’d expect it to be finished once the .save() call completed and execution continued. How are you determining it’s not done writing?

Because after the save line, I send the path to another machine via udp and this machine open it.
But sometimes the file is not fully written and opening fail. The time I get the fail msg, I go to path and the file is there and openable. So the udp msg is sent too fast after save.

That seems mighty odd. What’s the file system relationship like between those two machines? Is that file cached or transferred in a way where it might take time for it to move over? Or are they literally using the same device?

To rule PIL’s writing out you could try saving to an open file object instead, then flush/close it manually.

img = PIL.Image.open( input_filename )
out_file = open( output_filename, 'wb' )
img.save( out_file, 'JPEG' )  # Must specify desired format here
out_file.flush()
out_file.close()

Sortof a stab in the dark, though.

All machines are on same network. File is save on the network, then it just send a ‘ok’ msg with path to the file.
I though about sending directly the file content via udp, but being around 1mo I’m not fond of this trick.
Will test your idea, many thanks. Having a handle to the file should make it.

We’ve had problems like this that turned out to be antivirus scanning the file after write. There’s no good way to solve that short of just adding a delay and hoping for the best.

No scanning antivirus there. The solution above make things better but I still have some error. I’ve optimize the entire algorithm so I guess I will add a pause before opening the file.
Strange there isn’t a return from save function or something working.
Thanks

Ok, ever use the solution in another soft but totally forgotten this one lol
out_file = open(filePath, ‘wb’)
myimage.save(out_file, ‘PNG’)
out_file.flush()
os.fsync(out_file)
out_file.close()

More reading here :