Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
78 lines (60 loc) · 1.82 KB

File metadata and controls

78 lines (60 loc) · 1.82 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# _*_ coding: utf-8 _*_
"""
python_context.py by xianhu
"""
import contextlib
# 自定义打开文件操作
class MyOpen(object):
def __init__(self, file_name):
"""初始化方法"""
self.file_name = file_name
self.file_handler = None
return
def __enter__(self):
"""enter方法,返回file_handler"""
print("enter:", self.file_name)
self.file_handler = open(self.file_name, "r")
return self.file_handler
def __exit__(self, exc_type, exc_val, exc_tb):
"""exit方法,关闭文件并返回True"""
print("exit:", exc_type, exc_val, exc_tb)
if self.file_handler:
self.file_handler.close()
return True
# 使用实例
with MyOpen("python_base.py") as file_in:
for line in file_in:
print(line)
raise ZeroDivisionError
# 代码块中主动引发一个除零异常,但整个程序不会引发异常
# 内置库contextlib的使用
@contextlib.contextmanager
def open_func(file_name):
# __enter__方法
print("open file:", file_name, "in __enter__")
file_handler = open(file_name, "r")
yield file_handler
# __exit__方法
print("close file:", file_name, "in __exit__")
file_handler.close()
return
# 使用实例
with open_func("python_base.py") as file_in:
for line in file_in:
print(line)
break
# 内置库contextlib的使用
class MyOpen2(object):
def __init__(self, file_name):
"""初始化方法"""
self.file_handler = open(file_name, "r")
return
def close(self):
"""关闭文件,会被自动调用"""
print("call close in MyOpen2")
if self.file_handler:
self.file_handler.close()
return
# 使用实例
with contextlib.closing(MyOpen2("python_base.py")) as file_in:
pass
Morty Proxy This is a proxified and sanitized view of the page, visit original site.