python with as语法
import contextlib
class Pipeline(object):
def _publish(self, objects):
print('-------start')
print(objects)
# Imagine publication code here
pass
def _flush(self):
print('-------end')
# Imagine flushing code here
pass
@contextlib.contextmanager
def publisher(self):
try:
yield self._publish
finally:
self._flush()
pipeline = Pipeline()
with pipeline.publisher() as publisher:
publisher([1, 2, 3, 4])
print('-----------')
通过一条 with 语句同时打开两个文件
with open("file1", "r") as source, open("file2", "w") as destination:
destination.write(source.read())