我喜欢使用 with 语句来访问文件和数据库连接,因为如果出现错误或文件关闭,它会自动为我断开连接。
f = open('file.txt', 'r')
for i in f():
print(i)
f.close()
versus
with open('file.txt', 'r') as f:
for i in f:
print(i)
下面是否有从相机缓冲区读取的等效改写?:
c = cv.VideoCapture(0)
while(1):
_,f = c.read()
cv.imshow('e2',f)
if cv.waitKey(5)==27:
cv.waitKey()
break
c.release()
我试过了:
c = cv.VideoCapture(0)
while(1):
with c.read() as _,f:
cv.imshow('e2',f)
if cv.waitKey(5)==27:
cv.waitKey()
break
---没有运气。看起来拆卸/释放是一种不同的功能。这个习语在这里可以吗?
另一种方式使用contextlib.contextmanager https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager:
from contextlib import contextmanager
@contextmanager
def VideoCapture(*args, **kwargs):
cap = cv2.VideoCapture(*args, **kwargs)
try:
yield cap
finally:
cap.release()
(注意:已接受的答案已被编辑以包含此建议)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)