with在modbus_tk里出现了,感觉一脸懵逼
_LOCK = threading.RLock()
_HOOKS = {}
with _LOCK:
try:
for fct in _HOOKS[name]:
retval = fct(args)
if retval is not None:
return retval
except KeyError:
找找具体有什么用
确保使用过程中不管是否发生异常都会执行必须的’ 清理 ‘操作,并释放资源
也就是说不用
#1加入try和finally
f = open(r'c:\test.txt', 'r')
try:
data = f.read()
finally:
f.close()
#2不加入的版本
f = open(r'c:\test.txt', 'r')
data = f.read()
f.close()
实际上这么写就可以↓
with open(r'c:\test.txt', 'r') as f:
data = f.read()
#疑问
最上面的代码中 with 接了一个函数,但是在下面又有try和except