Python中with...as的用法
with...as语句是用来替换try...finally语句的,首先看下try...finally 的使用场景。try...finally一般用于异常处理情况,例如当打开一个文件时,无论发生什么情况我们都希望能把文件关闭。则我们可以这样写程序:#!/usr/bin/python#coding=utf-8import timetry:fd = open('ip1.txt'...
with...as语句是用来替换try...finally语句的,首先看下try...finally 的使用场景。try...finally一般用于异常处理情况,例如当打开一个文件时,无论发生什么情况我们都希望能把文件关闭。则我们可以这样写程序:
#!/usr/bin/python
#coding=utf-8
import time
try:
fd = open('ip1.txt','r')
while True:
line = fd.readline()
if len(line) == 0:
break;
print fd.readline()
time.sleep(2)
finally:
fd.close()
print ('run the last')
添加time.sleep(2)的目的是为了在每一行打印输出之后延时两秒,这时在cmd命令行下按下ctrl+c强制结束程序。运行结果如下:
192.168.1.9
run the last
Traceback (most recent call last):
File "__init__.py", line 12, in <module>
time.sleep(2)
KeyboardInterrupt
由此可见当异常发生时 finally语句后的程序块得到了运行。
有了with...as之后就可以用这一个命令替换try...finally语句,上面的例子可以改写为:
#!/usr/bin/python
#coding=utf-8
import time
with open('ip1.txt', 'r') as fd:
while True:
line = fd.readline()
if len(line) == 0:
break;
print fd.readline()
time.sleep(2)
with...as的基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。
紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。
#!/usr/bin/python
#coding=utf-8
class Example:
def __enter__(self):
print 'run __enter__()'
return 'this is a example'
def __exit__(self, type, value, trace):
print 'exit Example'
with Example() as str:
print 'example:', str
运行过程:1. 首先进入到Example的__enter__函数,并把函数的返回值赋给str
2. 执行with...as后面的语句
3. 执行__exit__函数
运行结果:
run __enter__()
example: this is a example
exit Example
更多推荐
所有评论(0)