我喜欢使用 with 语句来访问文件和数据库连接,因为如果发生错误或文件关闭,它会自动为我断开连接。
f = open('file.txt', 'r')
for i in f():
   print(i)
f.close()
相对
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
---没有运气。看起来拆卸/释放是一种不同的功能。这个成语在这里可以吗?