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

参考页面:

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

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

http://www.cnblogs.com/coser/archive/2013/01/28/2880328.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两三年了,还是不怎么习惯。写得少的缘故吧。

 

posted @   skytraveler  阅读(329)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示