|
| 1 | +>要使人晓得智慧和训诲,分辨通达的言语。使人处事,领受智慧、仁义、公平、正直的训诲。使愚人灵明、使少年人有知识和谋略。使智慧人听见、增长学问、使聪明人得着智谋、使人明白箴言和譬喻、懂得智慧人的言词和谜语。敬畏耶和华使知识的开端,愚妄人藐视智慧和训诲。 |
| 2 | +
|
| 3 | +#上下文管理器 |
| 4 | + |
| 5 | +在[《文件(1)》](./126.md)中提到,如果要打开文件,一种比较好的方法使使用`with`语句,因为这种方法,不仅结构简单,更重要的是不用再单独去判断某种异常情况,也不用专门去执行文件关闭的指令了。 |
| 6 | + |
| 7 | +本节对这个有点神奇的`with`进行深入剖析。 |
| 8 | + |
| 9 | +##概念 |
| 10 | + |
| 11 | +跟`with`相关的有一些概念,需要必须澄清。 |
| 12 | + |
| 13 | +**上下文管理** |
| 14 | + |
| 15 | +如果把它作为一个概念来阐述,似乎有点多余,因为从字面上也可以有一丝的体会,但是,我要说的是,那点直觉的体会不一定等于理性的严格定义,特别是周遭事物越来越复杂的时候。 |
| 16 | + |
| 17 | +“上下文”的英文是context,在网上检索了一下关于“上下文”的说法,发现没有什么严格的定义,另外,不同的语言环境,对“上下文管理”有不同的说法。根据我个人的经验和能看到的某些资料,我以为可以把“上下文”理解为某一些语句构成的一个环境(也可以说使代码块),所谓“管理”就是要在这个环境中做一些事情,做什么事情呢?就Python而言,是要将前面某个语句(“上文”)干的事情独立成为对象,然后在后面(“下文”)中使用这个对象来做事情。 |
| 18 | + |
| 19 | +**上下文管理协议** |
| 20 | + |
| 21 | +英文是Context Management Protocol,既然使协议,就应该是包含某些方法的东西,大家都按照这个去做(协商好了的东西)。Python中的上下文管理协议中必须包含`__enter__()`和`__exit__()`两个方法。 |
| 22 | + |
| 23 | +看这个两个方法的名字,估计读者也能领悟一二了(名字不是随便取的,这个某个岛国取名字的方法不同,当然,现在人家也不是随便取了)。 |
| 24 | + |
| 25 | +**上下文管理器** |
| 26 | + |
| 27 | +网上能够找到的最通常的说法是:上下文管理器使支持上下文管理协议的对象,这种对象实现了`__enter__()`和`__exit__()`方法。 |
| 28 | + |
| 29 | +这个简洁而准确的定义,一般情况下一些高手使理解了。如果读者有疑惑,就说明...,我还是要把一个高雅的定义通俗化更好一些。 |
| 30 | + |
| 31 | +在Python中,下面的语句,也存在上下文,但它们使一气呵成执行的。 |
| 32 | + |
| 33 | + >>> name = "laoqi" |
| 34 | + >>> if name == "laoqi": |
| 35 | + ... print name |
| 36 | + ... |
| 37 | + laoqi |
| 38 | + >>> if name == "laoqi": |
| 39 | + ... for i in name: |
| 40 | + ... print i, |
| 41 | + ... |
| 42 | + l a o q i |
| 43 | + |
| 44 | +以上两个例子中,“上文”进行了判断,然后“下文”执行,从上而下,已经很通畅了。还有不那么通畅的,就是下面的情况。 |
| 45 | + |
| 46 | + >>> f = open("a.txt", "w") |
| 47 | + >>> f.write("hello") |
| 48 | + >>> f.write("python") |
| 49 | + >>> f.close() |
| 50 | + |
| 51 | +在这个示例中,当`f = open("a.txt", "w")`之后,其实这句话并没有如同前面的示例中那样被“遗忘”,它是让计算机运行到一种状态——文件始终处于打开状态——然后在这种状态中进行后面的操作,直到`f.close()`为止,这种状态才结束。 |
| 52 | + |
| 53 | +在这种情况下,我们就可以使用“上下文管理器”(英文:Context Manager),用它来获得“上文”状态对象,然后在“下文”使用它,并在整个过程执行完毕来收场。 |
| 54 | + |
| 55 | +更Python一点的说法,可以说是在某任务执行之初,上下文管理器做好执行准备,当任务(代码块)执行完毕或者中间出现了异常,上下文管理器负责结束工作。 |
| 56 | + |
| 57 | +这么好的一个东西,是Python2.5以后才进来的。 |
| 58 | + |
| 59 | +##必要性 |
| 60 | + |
| 61 | +刚才那个向文件中写入hello和python两个单词的示例,如果你觉得在工程中也可以这样做,就大错特错了。因为它存在隐含的问题,比如在写入了hello之后,不知道什么原因,后面的python不能写入了,最能说服你的是恰好遇到了“磁盘已满”——虽然这种情况的概率可能比抓奖券还还小,但作为严禁的程序员,使必须要考虑的,这也是程序复杂之原因,这时候后面的操作就出现了异常,无法执行,文件也不能close。解决这个问题的方法使用`try ... finally ...`语句,读者一定能写出来。 |
| 62 | + |
| 63 | +不错,的确解决了。 |
| 64 | + |
| 65 | +问题继续,如果要从一个文件读内容,写入到另外一个文件中,下面的样子你觉得如何? |
| 66 | + |
| 67 | +首先建立一个文件,名称为23501.txt,里面的内容如下: |
| 68 | + |
| 69 | + $ cat 23501.txt |
| 70 | + hello laoqi |
| 71 | + www.itdiffer.com |
| 72 | + |
| 73 | +然后写出下面的代码,实现上述目的: |
| 74 | + |
| 75 | + |
| 76 | + #!/usr/bin/env python |
| 77 | + # coding=utf-8 |
| 78 | + |
| 79 | + read_file = open("23501.txt") |
| 80 | + write_file = open("23502.txt", "w") |
| 81 | + |
| 82 | + try: |
| 83 | + r = read_file.readlines() |
| 84 | + for line in r: |
| 85 | + write_file.write(line) |
| 86 | + finally: |
| 87 | + read_file.close() |
| 88 | + write_file.close() |
| 89 | + |
| 90 | +如果你不知道“上下文管理器”,这样做无可厚非,可偏偏现在已经知道了,所以,从今以后这样做就不是最优的了,因为它可以用“上下文管理器”写的更好。所以,用`with`语句改写之后,就是很优雅的了。 |
| 91 | + |
| 92 | + with open("23501.txt") as read_file, open("23503.txt", "w") as write_file: |
| 93 | + for line in read_file.readlines(): |
| 94 | + write_file.write(line) |
| 95 | + |
| 96 | +跟前面的对比一下,是不是有点惊叹了?!所以,你可以理直气壮地说“我用Python”。 |
| 97 | + |
| 98 | +可见上下文管理器是必要的,因为它让代码优雅了,当然优雅只是表象,还有更深层次的含义,继续阅读下面的内容能有深入体会。 |
| 99 | + |
| 100 | +**更深入** |
| 101 | + |
| 102 | +前面已经说了,上下文管理器执行了`__enter__()`和`__exit__()`方法,可是在`with`语句中哪里看到了这两个方法呢? |
| 103 | + |
| 104 | +为了解把这个问题解释清楚,需要先做点别的操作,虽然工程中一般不需要做。 |
| 105 | + |
| 106 | + |
| 107 | + #!/usr/bin/env python |
| 108 | + # coding=utf-8 |
| 109 | + |
| 110 | + class ContextManagerOpenDemo(object): |
| 111 | + |
| 112 | + def __enter__(self): |
| 113 | + print "Starting the Manager." |
| 114 | + |
| 115 | + def __exit__(self, *others): |
| 116 | + print "Exiting the Manager." |
| 117 | + |
| 118 | + with ContextManagerOpenDemo(): |
| 119 | + print "In the Manager." |
| 120 | + |
| 121 | +在上面的代码示例中,我们写了一个类`ContextManagerOpenDemo()`,你就把它理解为我自己写的`Open()`吧,当然使最简版本了。在这个类中,`__enter__()`方法和`__exit__()`方法都比较简单,就是要检测是否执行该方法。 |
| 122 | + |
| 123 | +然后用`with`语句来执行,目的是按照“上下文管理器”的解释那样,应该首先执行类中的`__enter__()`方法,它总是在进入代码块前被调用的,接着就执行代码块——`with`语句下面的内容,当代码块执行完毕,离开的时候又调用类中的`__exit__()`。 |
| 124 | + |
| 125 | +检验一下,是否按照上述理想路径执行。 |
| 126 | + |
| 127 | + $ python 23502.py |
| 128 | + Starting the Manager. |
| 129 | + In the Manager. |
| 130 | + Exiting the Manager. |
| 131 | + |
| 132 | +果然如此。执行结果已经基本显示了上下文管理器的工作原理。 |
| 133 | + |
| 134 | +为了让它更接近`open()`,需要再进一步改写,让它能够接受参数,以便于指定打开的文件。 |
| 135 | + |
| 136 | + #!/usr/bin/env python |
| 137 | + # coding=utf-8 |
| 138 | + |
| 139 | + class ContextManagerOpenDemo(object): |
| 140 | + def __init__(self, filename, mode): |
| 141 | + self.filename = filename |
| 142 | + self.mode = mode |
| 143 | + |
| 144 | + def __enter__(self): |
| 145 | + print "Starting the Manager." |
| 146 | + self.open_file = open(self.filename, self.mode) |
| 147 | + return self.open_file |
| 148 | + |
| 149 | + def __exit__(self, *others): |
| 150 | + self.open_file.close() |
| 151 | + print "Exiting the Manager." |
| 152 | + |
| 153 | + with ContextManagerOpenDemo("23501.txt", 'r') as reader: |
| 154 | + print "In the Manager." |
| 155 | + for line in reader: |
| 156 | + print line |
| 157 | + |
| 158 | +这段代码的意图主要是: |
| 159 | + |
| 160 | +1. 通过`__init__()`能够读入文件名和打开模式,以使得看起来更接近`open()`; |
| 161 | +2. 当进入语句块时,先执行`__enter__()`方法,把文件打开,并返回该文件对象; |
| 162 | +3. 执行代码块内容,打印文件内容; |
| 163 | +4. 离开代码块的时候,执行`__exit__()`方法,关闭文件。 |
| 164 | + |
| 165 | +运行结果是: |
| 166 | + |
| 167 | + $ python 23502.py |
| 168 | + Starting the Manager. |
| 169 | + In the Manager. |
| 170 | + hello laoqi |
| 171 | + |
| 172 | + www.itdiffer.com |
| 173 | + |
| 174 | + Exiting the Manager. |
| 175 | + |
| 176 | +在上述代码中,我们没有对异常进行处理,也就是把异常隐藏了,不管在代码块执行时候遇到什么异常,都是要离开代码块,那么就立刻让`__exit__()`方法接管了。 |
| 177 | + |
| 178 | +如果要把异常显现出来,也使可以,可以改写`__exit__()`方法。例如: |
| 179 | + |
| 180 | + def __exit__(self, exc_type, exc_value, exc_traceback): |
| 181 | + return False |
| 182 | + |
| 183 | +当代码块出现异常,则由`__exit__()`负责善后清理,如果返回False,如上面的示例,则异常让`with`之外的语句逻辑来处理,这是通常使用的方法;如果返回True,意味着不对异常进行处理。 |
| 184 | + |
| 185 | +从上面我们自己写的类和方法中,已经了解了上下文管理器的运行原理了。那么,`open()`跟它有什么关系吗? |
| 186 | + |
| 187 | +为了能清楚地查看,我们需要建立一个文件对象,并且使用`dir()`来看看是否有我们所期盼的东西。 |
| 188 | + |
| 189 | + >>> f = open("a.txt") |
| 190 | + >>> dir(f) |
| 191 | + ['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] |
| 192 | + |
| 193 | +读者是否运用你那迷迷糊糊的火眼金睛看到了两个已经很面熟的方法名称了?如果你找到了,你就心知肚明了。 |
| 194 | + |
| 195 | +在`with`语句中还有一个`as`,虽然在上面示例中没有显示,但是一般我们还是不抛弃它的,它的作用就是将返回的对象付给一个变量,以便于以后使用。 |
| 196 | + |
| 197 | +##contextlib模块 |
| 198 | + |
| 199 | +Python中的这个模块使上下文管理中非常好用的东东,这也是标准库中的一员,不需要另外安装了。 |
| 200 | + |
| 201 | + >>> import contextlib |
| 202 | + >>> dir(contextlib) |
| 203 | + ['GeneratorContextManager', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'closing', 'contextmanager', 'nested', 'sys', 'warn', 'wraps'] |
| 204 | + |
| 205 | +常用的是`contextmanger`、`closing`和`nested`。 |
| 206 | + |
| 207 | +###contextlib.closing() |
| 208 | + |
| 209 | +要想知道`contextlib.closing()`的使用方法,最常用的方法就是`help()`,这是我们的一贯做法,胜过查阅其它任何资料。 |
| 210 | + |
| 211 | + Help on class closing in module contextlib: |
| 212 | + |
| 213 | + class closing(__builtin__.object) |
| 214 | + | Context to automatically close something at the end of a block. |
| 215 | + | |
| 216 | + | Code like this: |
| 217 | + | |
| 218 | + | with closing(<module>.open(<arguments>)) as f: |
| 219 | + | <block> |
| 220 | + | |
| 221 | + |
| 222 | +以上省略了部分内容。 |
| 223 | + |
| 224 | +有一种或许常用到的情景,就是连接数据库,并返回一个数据库对象,在使用完之后关闭数据库连接,其形状如下: |
| 225 | + |
| 226 | + with contextlib.closing(CreateDB()) as db: |
| 227 | + db.query() |
| 228 | + |
| 229 | +以上不是可运行的代码,只是一个架势,读者如果在编码中使用,需要根据实际情况改写。 |
| 230 | + |
| 231 | +当数据库语句`db.query()`结束之后,数据库连接自动关闭。 |
| 232 | + |
| 233 | +###contextlib.nested() |
| 234 | + |
| 235 | +nested的汉语意思是“嵌套的,内装的”,从字面上读者也可能理解了,这个方法跟嵌套有关。前面有一个示例,是从一个文件读取,然后写入到另外一个文件。我不知道读者是否想过可以这么写: |
| 236 | + |
| 237 | + with open("23501.txt") as read_file: |
| 238 | + open("23503.txt", "w") as write_file: |
| 239 | + for line in read_file.readlines(): |
| 240 | + write_file.write(line) |
| 241 | + |
| 242 | +此种写法不是不行,但是不提倡,因为它太不Pythoner了。其实这里就涉及到了嵌套,因此可以使用`contextlib.nested`重。 |
| 243 | + |
| 244 | + with contextlib.nested(open("23501.txt", "r"), open("23503.txt", "w")) as (read_file, write_file): |
| 245 | + for line in read_file.readlines(): |
| 246 | + write_file.write(line) |
| 247 | + |
| 248 | + |
0 commit comments