安全的pythonic方法来捕获pyglet错误

时间:2018-06-16 21:02:30

标签: python error-handling pyglet

如果我跑:

import pyglet

window = pyglet.window.Window()
image = pyglet.resource.image('/path/with/an/error/image.png')

@window.event
def on_draw():
    window.clear()
    image.blit(0, 0)

pyglet.app.run()

来自pyglet文档,然后

    ResourceNotFoundException: Resource "/path/with/an/error/image.png" was not found on the path.  Ensure that the filename has the correct captialisation.

哪都好! 这是我的问题:对象窗口保持打开状态,除非我杀死了python进程:

 kill -9 <corresponding python process number>

如果您正在寻找此问题的解决方案,可以找到它here

如果我改为跑:

 import pyglet

 image_location = "/path/with/an/error/image.png"

 try:
     window = pyglet.window.Window()
     image = pyglet.resource.image(image_location)

     @window.event
     def on_draw():
         window.clear()
         image.blit(0, 0)

     pyglet.app.run()

 except ValueError:
     print ValueError
     print "there was an error"

 finally:
     window.close()

然后关闭对象窗口。我的问题是:

这个脚本真的安全吗?

是否有更pythonic方法来处理pyglet中的错误?

注意:

 with pyglet.window.Window() as window:  
    ...

返回错误:

 You are using the with statement. It requires an object with __enter__ and __exit__ methods.

0 个答案:

没有答案