是否可以使用Python "with"使用 ogr.open(file) 函数的语句?
例如,我想做这样的事情:
with ogr.open(file) as ds:
目前,我只能执行以下操作:
try:
ds = ogr.open(file)
...
except:
del ds
最佳答案
根据文档,您似乎无法将 与 ogr.Open(file) 一起使用
...
在 with
语句中使用的 Python 对象需要具有方法 __enter__
和 __exit__
来设置和删除所使用的上下文在 with
block 内。 Here's an explanation .
根据Documentation for OGR Open ,这些 __enter__
和 __exit__
方法不是为 Open
返回的 DataSource 对象定义的,因此您无法使用 ogr.Open 的结果
作为 with
语句的主语。
所以看来您必须使用 try
/ except
组合(尽管 try
/finally
组合可能会更好)。
关于python - 使用 Python "with"语句进行 ogr.open(file),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37981614/