首页 > 代码库 > with补充知识点

with补充知识点

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补充知识点