test 1
import contextlib
@contextlib.contextmanager
def a():
print(1)
yield
print(3)
with a() as q:
print(2)
test 2
import contextlib
@contextlib.contextmanager
def b():
try:
yield
except Exception as error:
print('error:',error)
with b():
1/0
test 3
import contextlib
class c:
def d(self):
print('start')
def close(self):
print('game over!')
with contextlib.closing(c()) as c_obj:
print('contextlib.close()')
test 4
with open('a.jpg', 'rb') as from_file, open('b.jpg', 'wb') as to_file:
to_file.write(from_file.read())
©本文由简书作者:清风Python 原创 如需转载请注明