python模块之contexlib
一、上下文管理器
with是python实现上下文管理器的核心关键词。它能够在代码执行前和执行后做一些额外的事情。
最常见的代码恐怕就是文件操作了。
with open("file", "r", encoding="utf-8") as f:
data = f.read()
import functools
reader = functools.partial(open, mode="r", encoding="utf-8")
f = reader("homework/user.txt")
f.readlines()
实际上,with语句是通过__enter__和__exit__来实现的。
class Open(object):
def __init__(self, file, mode, encoding="GBK"):
"""初始化,生成文件句柄"""
self.file = file
self.mode = mode
self.encoding = encoding def __enter__(self):
print("__enter__ has called.")
try:
f = open(self.file, self.mode, self.encoding)
return f
except Exception as e:
print(e) def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__ has called.")
print("exc_type: ", exc_type)
print("exc_val: ", exc_val)
print("exc_tb: ", exc_tb) with Open("有关协议.docx", mode='r', encoding="GBK") as f:
data = f.readlines() """
__enter__ has called.
an integer is required (got type str) # 异常提示信息
__exit__ has called.
exc_type: <class 'AttributeError'>
exc_val: 'NoneType' object has no attribute 'readlines'
exc_tb: <traceback object at 0x110ade608>
"""
with在开始时调用__enter__,并将结果赋给as后面的变量f。在结束时会调用__exit__,如果有异常,则会把异常类型、异常值和跟踪地址作为参数传递给__eixt__。
如果我们自己使用with,则必须在定义的类中实现__enter__和__exit__方法。
二、contextlib模块
python3内置了contextlib模块来帮助我们更加方便地实现上下文管理器。
import contextlib
@contextlib.contextmanager
def file_open(file_name, mode="r", encoding="utf-8"):
print("file open")
yield open(file_name, mode=mode, encoding=encoding)
print("file end") with file_open("log.txt") as f:
print("Read file.")
print(f)
dic = f.read()
print(dic)
contextlib必须调用装饰器来装饰一个需要使用with语句的函数。在函数内部必须要使用yield将该函数变成可迭代对象。
在with时,将yield返回值赋给as后的变量。此时已执行到yield时。f包裹的内容作为do something继续执行。最后才会执行file end。
python模块之contexlib的更多相关文章
- 使用C/C++写Python模块
最近看开源项目时学习了一下用C/C++写python模块,顺便把学习进行一下总结,废话少说直接开始: 环境:windows.python2.78.VS2010或MingW 1 创建VC工程 (1) 打 ...
- Python模块之configpraser
Python模块之configpraser 一. configpraser简介 用于处理特定格式的文件,其本质还是利用open来操作文件. 配置文件的格式: 使用"[]"内包含 ...
- Python模块之"prettytable"
Python模块之"prettytable" 摘要: Python通过prettytable模块可以将输出内容如表格方式整齐的输出.(对于用Python操作数据库会经常用到) 1. ...
- python 学习第五天,python模块
一,Python的模块导入 1,在写python的模块导入之前,先来讲一些Python中的概念性的问题 (1)模块:用来从逻辑上组织Python代码(变量,函数,类,逻辑:实现一个功能),本质是.py ...
- windows下安装python模块
如何在windows下安装python模块 1. 官网下载安装包,比如(pip : https://pypi.python.org/pypi/pip#downloads) pip-9.0.1.tar. ...
- 安装第三方Python模块,增加InfoPi的健壮性
这3个第三方Python模块是可选的,不安装的话InfoPi也可以运行. 但是如果安装了,会增加InfoPi的健壮性. 目录 1.cchardet 自动检测文本编码 2.lxml 用于解析 ...
- Python基础篇【第5篇】: Python模块基础(一)
模块 简介 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就 ...
- python 模块加载
python 模块加载 本文主要介绍python模块加载的过程. module的组成 所有的module都是由对象和对象之间的关系组成. type和object python中所有的东西都是对象,分为 ...
- pycharm安装python模块
这个工具真的好好,真的很喜欢,它很方便,很漂亮,各种好 pycharm安装python模块:file-setting-搜索project inte OK
随机推荐
- java内存模型(jMM)(二)
volatile关键字 volatile是一个类型修饰符(type specifier),就像大家更熟悉的const一样,它是被设计用来修饰被不同线程访问和修改的变量.volatile的作用是作为指令 ...
- JMeter—监听器
用来显示JMeter取样器的测试结果,能够以树.表.图形形式显示,也可以以文件方式保存. 一.设置默认配置 初始化配置文件设置: 监听器默认保存哪些数据域,可以在jmeter.properties(或 ...
- UIView-frame-VS-bounds
分享链接
- css 清楚浮动三种方法
我们可以看到这样一个布局: <style> .left{ width: 200px; height: 200px; background-color: #00ee00; float: le ...
- UICollectionView 自定义横向排版
.h #import <UIKit/UIKit.h> @interface JHCollectionViewFlowLayout : UICollectionViewFlowLayout ...
- Centos 7.6 安装selenium+firefox+google chrome(支持xshell运行)
1. 查看Linux 版本 [root@penguin selenium]# cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core) ...
- 接上篇—用spring注入DBbean,并使用maven管理
接着上篇的登陆功能,用spring的依赖注入和maven的管理,又实现了一遍.新增了注册功能. 有两个目标:使用spring和使用maven 目录结构 首先是目标1:使用spring的依赖注入,注入b ...
- UML-5-进化式需求
1.需求管理定义 瀑布式式中,研发之前,完全定义和固化需求. 但,需求是不断变化的,你之前可能会有45%的需求,不会被使用到,经常使用到的只占20%左右. 因此,如何寻找这20%的需求,是重点.其方法 ...
- git常用安装包,指令
babel-polufill -es6 API转义 npm install --save @babel/polyfill babel-runtime -es语法转义 npm install --s ...
- Python 自定义iterator生成器
#计数版 class countdown(object): def __init__(self,start): self.start = start def __iter__(self): retur ...