blob: 22fc43d7081fd1bfb7abb9bddd1f4c8fbc02ab06 (
plain)
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
|
# -*- coding: utf-8 -*-
import six
import sys
class open_file:
"""
Context manager that opens a filename and closes it on exit, but does
nothing for file-like objects.
"""
def __init__(self, filename, *args, **kwargs) -> None:
self.closing = kwargs.pop("closing", False)
if filename is None:
stream = sys.stdout if "w" in args else sys.stdin
if six.PY3:
self.fh = open(stream.fileno(), *args, **kwargs)
else:
self.fh = stream
elif isinstance(filename, six.string_types):
self.fh = open(filename, *args, **kwargs)
self.closing = True
else:
self.fh = filename
def __enter__(self):
return self.fh
def __exit__(self, exc_type, exc_val, exc_tb):
if self.closing:
self.fh.close()
return False
|