Skip to content

With和上下文管理器

在使用系统资源比如说文件, socket, 数据库连接的时候, 打开这一些资源以后需要关闭, 不关闭的话, 文件的打开数量等资源的数量是有限的

如果一个为文件关闭的打开的过程中报错, 这一个文件的关闭可能出现问具体, 可以使用try进行异常捕获, 也可以使用with语句

上下文

实际是代码的执行环境

上下文管理器

任何一个实现了__enter__()__exit()__两个方法的对象都可以使用with进行管理

python
class File(object):
    def __init__(self, filename, mode) -> None:
        self.filename = filename
        self.mode = mode
    
    def __enter__(self):
        print("Opening the file...")
        self.file = open(self.filename, self.mode)
        return self.file
    
    def __exit__(self, *args):
        # 这一个函数在调用的时候传入参数, 所以需要*args去获取这些参数
        print("Closing the file...")
        self.file.close()

with File('test.txt', 'w') as f:
    print("Writing to the file...")
    f.write("Hello, World!")

with开始的时候会调用__enter__, 离开的时候会使用__exit__

bash
PS E:\JHY\python\2024-4-22> python -u "e:\JHY\python\2024-4-22\main.py"
Opening the file...
Writing to the file...      
Closing the file...

更简单的调用

python
from contextlib import contextmanager

@contextmanager
def my_context_manager():
    print('Enter')
    yield
    print('Exit')

with my_context_manager():
    print('Inside')
bash
PS E:\JHY\python\2024-4-22> python -u "e:\JHY\python\2024-4-22\main.py"
Enter
Inside
Exit
python
from contextlib import contextmanager

@contextmanager
def my_open(filename, mode):
    f = open(filename, mode)
    yield f
    f.close()

with my_open('test.txt', 'r') as f:
    print(f.readlines())
bash
PS E:\JHY\python\2024-4-22> python -u "e:\JHY\python\2024-4-22\main.py"
['1.Hello\n', '2.World\n']

实际使用的时候可以直接with oprn(filename, mode) as f:这一个f里面已经实现了这两个规则

总结

在开发里面使用系统资源一定需要关闭的时候, 为了避免资源在异常的时候没有正常的关闭, 所以使用这一个用于管理资源