码迷,mamicode.com
首页 > 其他好文 > 详细

with补充知识点

时间:2017-01-15 17:01:41      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:read   finally   关闭   called   odi   打开   nal   err   call   

import threading,queue,time
import contextlib

@contextlib.contextmanager
def fun(list_1,val):
    list_1.append(val)
    try:
        yield
    finally:
        list_1.remove(val)


q = queue.Queue()

q.put(‘alxe‘)
li = []

with fun(li,1):
    q.get()

  

class A:
    def __enter__(self):
        print (‘__enter__() called‘)

    def __exit__(self, e_t, e_v, t_b):
        print (‘__exit__() called‘)

with A() as a:
    print(‘got instance‘)

  

from __future__ import with_statement
from contextlib import contextmanager

@contextmanager
def context():
    print (‘entering the zone‘)
    try:
        yield
    except Exception as e:
        print (‘with an error %s‘%e)
        raise e
    else:
      print (‘with no error‘)

with context():
    print (‘----in context call------‘)

  

文件打开关闭
import contextlib

@contextlib.contextmanager
def myopen(file_path,mode):
    f = open(file_path,mode,encoding=‘utf-8‘)
    try:
        yield f

    finally:
        f.close()

with myopen(‘D:\E\semantic/sd.txt‘,‘r‘) as file_obj:
    print(file_obj.read())

  

with补充知识点

标签:read   finally   关闭   called   odi   打开   nal   err   call   

原文地址:http://www.cnblogs.com/cloniu/p/6287331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!