-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathcontext_manager_tutorial.py
More file actions
55 lines (41 loc) · 974 Bytes
/
context_manager_tutorial.py
File metadata and controls
55 lines (41 loc) · 974 Bytes
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
import time
from contextlib import contextmanager
@contextmanager
def my_context():
# do things in enter ( __enter__ )
yield
# do things post ( __exit__ )
@contextmanager
def tag(name):
print('<{}>'.format(name))
yield 'HIHI~'
print('</{}>'.format(name))
@contextmanager
def elapsed_time(name=''):
start_time = time.time()
yield
end_time = time.time() - start_time
print(name, '{:.2f}'.format(end_time))
@contextmanager
def try_catch():
try:
yield 'okok'
except Exception as e:
print("e=%s" % str(e))
finally:
print('stop')
if __name__ == '__main__':
# tutorial_1
with tag('h1') as data:
print('hello')
print(data)
# tutorial_2
# with tag('h1'), tag('p'):
# print('hello')
# tutorial_3
# with elapsed_time('block'):
# time.sleep(2)
# tutorial_4
# with try_catch() as data:
# print(data)
# source = 1/0