set thing up try: do something except : handle exception finally: tear thing down
#!/usr/bin/env python
from __future__ import with_statement
filename = 'for_test.txt'
def output(content):
print content
#functio solution
def controlled_execution(func):
#prepare thing
f = None
try:
#set thing up
f = open(filename, 'r')
content = f.read()
if not callable(func):
return
#deal with thing
func(content)
except IOError, e:
print 'Error %s' % str(e)
finally:
if f:
#tear thing down
f.close()
def test():
controlled_execution(output)
test()
#yield solution
def controlled_execution():
f = None
try:
f = open(filename, 'r')
thing = f.read()
#for thing in f:
yield thing
except IOError,e:
print 'Error %s' % str(e)
finally:
if f:
f.close()
def test2():
for content in controlled_execution():
output(content)
#class solution
class controlled_execution(object):
def __init__(self):
self.f = None
def __enter__(self):
try:
f = open(filename, 'r')
content = f.read()
return content
except IOError ,e:
print 'Error %s' % str(e)
#return None
def __exit__(self, type, value, traceback):
if self.f:
print 'type:%s, value:%s, traceback:%s' % \
(str(type), str(value), str(traceback))
self.f.close()
def test3():
with controlled_execution() as thing:
if thing:
output(thing)
def test4():
with open(filename, 'r') as f:
output(f.read())
print f.read()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有