开发者

Python: How to ensure the last line of code has completed?

I'm doing some kind of complex operation, it needs the last line(s) of code has completed, then proceed to the next step, for example. I need to ensure a file 开发者_如何学Gohas written on the disk then read it. Always, the next line of code fires while the file haven't written on disk , and thus error came up. How resolve this?

Okay..

picture.save(path, format='png')
time.sleep(1)       #How to ensure the last step has finished
im = Image.open(path)


You do not need to do anything unless the previous operation is asynchronous. In your case, you should check picture.save's documentation to see if it specifically define as asynchronous. By default everything is synchronize. Each line will complete before it continues to next operation.


Seems like you just want to check is that there's a file at path before trying to open it.

You could check for the path's existence before trying to open it and sleep for a bit if it doesn't exist, but that sleep might not be long enough, and you still might have a problem opening the file.

You really should just enclose the open operation in a try-except block:

try:
    im = Image.open(path)
except [whatever exception you are getting]:
    # Handle the fact that you couldn't open the file
    im = None # Maybe like this..
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜