filename = 'my_file.txt'
mode = 'w' # Mode that allows to write to the file
writer = open(filename, mode)
writer.write('Hello ')
writer.write('World')
writer.close()
writer = open(filename, mode)
try:
writer.write('Hello ')
writer.write('World')
finally:
writer.close()
with open(filename, mode) as writer:
writer.write('Hello ')
writer.write('World')
class PypixContextManagerDemo:
def __enter__(self):
print 'Entering the block'
def __exit__(self, *unused):
print 'Exiting the block'
with PypixContextManagerDemo():
print 'In the block'
#Output:
#Entering the block
#In the block
#Exiting the block
class PypixOpen:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.openedFile = open(self.filename, self.mode)
return self.openedFile
def __exit__(self, *unused):
self.openedFile.close()
with PypixOpen(filename, mode) as writer:
writer.write("Hello World from our new Context Manager!")
def __exit__(self, exc_type, exc_val, exc_tb)
class RaiseOnlyIfSyntaxError:
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
return SyntaxError != exc_type
class assert_raises(object):
# based on pytest and unittest.TestCase
def __init__(self, type):
self.type = type
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
if type is None:
raise AssertionError('exception expected')
if issubclass(type, self.type):
return True # swallow the expected exception
raise AssertionError('wrong exception type')
with assert_raises(KeyError):
{}['foo']
with contextlib.closing(CreateDatabase()) as database: database.query()
with open('toReadFile', 'r') as reader:
with open('toWriteFile', 'w') as writer:
writer.writer(reader.read())
with contextlib.nested(open('fileToRead.txt', 'r'),
open('fileToWrite.txt', 'w')) as (reader, writer):
writer.write(reader.read())
with open('fileToRead.txt', 'r') as reader, \
open('fileToWrite.txt', 'w') as writer:
writer.write(reader.read())
contextlib.contextmanager
import threading lock = threading.Lock() def safeWriteToFile(openedFile, content): lock.acquire() openedFile.write(content) lock.release()
@contextlib.contextmanager def loudLock(): print 'Locking' lock.acquire() yield print 'Releasing' lock.release() with loudLock(): print 'Lock is locked: %s' % lock.locked() print 'Doing something that needs locking' #Output: #Locking #Lock is locked: True #Doing something that needs locking #Releasing
@contextlib.contextmanager
def loudLock():
print 'Locking'
with lock:
yield
print 'Releasing'
@contextlib.contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
@contextlib.contextmanager
def closing(obj):
try:
yield obj
finally:
obj.close()
@contextlib.contextmanager
def assert_raises(type):
try:
yield
except type:
return
except Exception as value:
raise AssertionError('wrong exception type')
else:
raise AssertionError('exception expected')
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有