您的位置:首页 > 编程语言 > Python开发

RF源码阅读(碎片纪录)-Python积木之contextlib

2013-12-26 00:17 369 查看
参考页面:

http://docs.python.org/2/library/contextlib.html

contextlib是为了配合with语句来使用的。使用起来更加简洁。本来想写一下,这位同仁已经写得非常棒了。给个链接,就不自己费劲写了:

/article/5038534.html

感谢!

RF的入口程序run.py继承了util/Application类(application.py)中。里面的一个核心函数就利用到了contextlib

def execute_cli(self, cli_arguments):
with self._logging():
options, arguments = self._parse_arguments(cli_arguments)
rc = self._execute(arguments, options)
self._exit(rc)

@contextmanager
def _logging(self):
self._logger.register_file_logger()
self._logger.info('%s %s' % (self._ap.name, self._ap.version))
try:
yield
finally:
self._logger.close()


这段代码会先执行

self._logger.register_file_logger()
self._logger.info('%s %s' % (self._ap.name, self._ap.version))

再执行

options, arguments = self._parse_arguments(cli_arguments)

rc = self._execute(arguments, options)

最后执行 finally的 self._logger.close()

with 块执行完以后,会执行

self._exit(rc)

说实在的有一点不符合我原有的思维习惯。断断续续用python两三年了,还是不怎么习惯。写得少的缘故吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: