File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ from contextlib import contextmanager
5+
6+ @contextmanager
7+ def closing (fname ):
8+ f = None
9+ try :
10+ f = open (fname , 'r' )
11+ yield f
12+ finally :
13+ if f :
14+ f .close ()
15+
16+ with closing ('test.txt' ) as f :
17+ print (f .read ())
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ import os
5+
6+ from contextlib import suppress
7+
8+ with suppress (FileNotFoundError ):
9+ os .remove ('tempfile.1' )
10+ os .remove ('tempfile.2' )
11+ os .remove ('tempfile.3' )
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ from contextlib import contextmanager
5+
6+ @contextmanager
7+ def log (name ):
8+ print ('[%s] start...' % name )
9+ yield
10+ print ('[%s] end.' % name )
11+
12+ with log ('DEBUG' ):
13+ print ('Hello, world!' )
14+ print ('Hello, Python!' )
You can’t perform that action at this time.
0 commit comments