Explicitly close some files (from issue #10093)

This commit is contained in:
Antoine Pitrou 2010-10-14 21:15:17 +00:00
parent d9f57630fe
commit b86680e299
6 changed files with 31 additions and 14 deletions

View File

@ -383,7 +383,8 @@ def main():
if o == '-u': func = decode if o == '-u': func = decode
if o == '-t': test(); return if o == '-t': test(); return
if args and args[0] != '-': if args and args[0] != '-':
func(open(args[0], 'rb'), sys.stdout.buffer) with open(args[0], 'rb') as f:
func(f, sys.stdout.buffer)
else: else:
func(sys.stdin.buffer, sys.stdout.buffer) func(sys.stdin.buffer, sys.stdout.buffer)

View File

@ -199,9 +199,8 @@ class MimeTypes:
list of standard types, else to the list of non-standard list of standard types, else to the list of non-standard
types. types.
""" """
fp = open(filename) with open(filename) as fp:
self.readfp(fp, strict) self.readfp(fp, strict)
fp.close()
def readfp(self, fp, strict=True): def readfp(self, fp, strict=True):
""" """
@ -348,7 +347,7 @@ def init(files=None):
files = knownfiles files = knownfiles
for file in files: for file in files:
if os.path.isfile(file): if os.path.isfile(file):
db.readfp(open(file)) db.read(file)
encodings_map = db.encodings_map encodings_map = db.encodings_map
suffix_map = db.suffix_map suffix_map = db.suffix_map
types_map = db.types_map[True] types_map = db.types_map[True]

View File

@ -333,7 +333,8 @@ def _init_posix(vars):
# load the installed pyconfig.h: # load the installed pyconfig.h:
config_h = get_config_h_filename() config_h = get_config_h_filename()
try: try:
parse_config_h(open(config_h), vars) with open(config_h) as f:
parse_config_h(f, vars)
except IOError as e: except IOError as e:
msg = "invalid Python installation: unable to open %s" % config_h msg = "invalid Python installation: unable to open %s" % config_h
if hasattr(e, "strerror"): if hasattr(e, "strerror"):

View File

@ -4160,7 +4160,8 @@ class TestEncoding(TestCase):
def _test_module_encoding(self, path): def _test_module_encoding(self, path):
path, _ = os.path.splitext(path) path, _ = os.path.splitext(path)
path += ".py" path += ".py"
codecs.open(path, 'r', 'utf8').read() with codecs.open(path, 'r', 'utf8') as f:
f.read()
def test_argparse_module_encoding(self): def test_argparse_module_encoding(self):
self._test_module_encoding(argparse.__file__) self._test_module_encoding(argparse.__file__)

View File

@ -602,10 +602,13 @@ def parsefile():
<ns0:empty-element /> <ns0:empty-element />
</ns0:root> </ns0:root>
>>> with open(SIMPLE_XMLFILE) as f:
... data = f.read()
>>> parser = ET.XMLParser() >>> parser = ET.XMLParser()
>>> parser.version # doctest: +ELLIPSIS >>> parser.version # doctest: +ELLIPSIS
'Expat ...' 'Expat ...'
>>> parser.feed(open(SIMPLE_XMLFILE).read()) >>> parser.feed(data)
>>> print(serialize(parser.close())) >>> print(serialize(parser.close()))
<root> <root>
<element key="value">text</element> <element key="value">text</element>
@ -614,7 +617,7 @@ def parsefile():
</root> </root>
>>> parser = ET.XMLTreeBuilder() # 1.2 compatibility >>> parser = ET.XMLTreeBuilder() # 1.2 compatibility
>>> parser.feed(open(SIMPLE_XMLFILE).read()) >>> parser.feed(data)
>>> print(serialize(parser.close())) >>> print(serialize(parser.close()))
<root> <root>
<element key="value">text</element> <element key="value">text</element>
@ -624,7 +627,7 @@ def parsefile():
>>> target = ET.TreeBuilder() >>> target = ET.TreeBuilder()
>>> parser = ET.XMLParser(target=target) >>> parser = ET.XMLParser(target=target)
>>> parser.feed(open(SIMPLE_XMLFILE).read()) >>> parser.feed(data)
>>> print(serialize(parser.close())) >>> print(serialize(parser.close()))
<root> <root>
<element key="value">text</element> <element key="value">text</element>
@ -727,7 +730,8 @@ def iterparse():
end-ns None end-ns None
>>> events = ("start", "end", "bogus") >>> events = ("start", "end", "bogus")
>>> context = iterparse(SIMPLE_XMLFILE, events) >>> with open(SIMPLE_XMLFILE, "rb") as f:
... iterparse(f, events)
Traceback (most recent call last): Traceback (most recent call last):
ValueError: unknown event 'bogus' ValueError: unknown event 'bogus'
@ -779,6 +783,8 @@ def custom_builder():
""" """
Test parser w. custom builder. Test parser w. custom builder.
>>> with open(SIMPLE_XMLFILE) as f:
... data = f.read()
>>> class Builder: >>> class Builder:
... def start(self, tag, attrib): ... def start(self, tag, attrib):
... print("start", tag) ... print("start", tag)
@ -788,7 +794,7 @@ def custom_builder():
... pass ... pass
>>> builder = Builder() >>> builder = Builder()
>>> parser = ET.XMLParser(target=builder) >>> parser = ET.XMLParser(target=builder)
>>> parser.feed(open(SIMPLE_XMLFILE, "r").read()) >>> parser.feed(data)
start root start root
start element start element
end element end element
@ -798,6 +804,8 @@ def custom_builder():
end empty-element end empty-element
end root end root
>>> with open(SIMPLE_NS_XMLFILE) as f:
... data = f.read()
>>> class Builder: >>> class Builder:
... def start(self, tag, attrib): ... def start(self, tag, attrib):
... print("start", tag) ... print("start", tag)
@ -811,7 +819,7 @@ def custom_builder():
... print("comment", repr(data)) ... print("comment", repr(data))
>>> builder = Builder() >>> builder = Builder()
>>> parser = ET.XMLParser(target=builder) >>> parser = ET.XMLParser(target=builder)
>>> parser.feed(open(SIMPLE_NS_XMLFILE, "r").read()) >>> parser.feed(data)
pi pi 'data' pi pi 'data'
comment ' comment ' comment ' comment '
start {namespace}root start {namespace}root
@ -829,7 +837,8 @@ def getchildren():
""" """
Test Element.getchildren() Test Element.getchildren()
>>> tree = ET.parse(open(SIMPLE_XMLFILE, "rb")) >>> with open(SIMPLE_XMLFILE, "rb") as f:
... tree = ET.parse(f)
>>> for elem in tree.getroot().iter(): >>> for elem in tree.getroot().iter():
... summarize_list(elem.getchildren()) ... summarize_list(elem.getchildren())
['element', 'element', 'empty-element'] ['element', 'element', 'empty-element']

View File

@ -208,6 +208,7 @@ _Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent)
PyObject *binary; PyObject *binary;
PyObject *fob = NULL; PyObject *fob = NULL;
PyObject *lineobj = NULL; PyObject *lineobj = NULL;
PyObject *res;
char buf[MAXPATHLEN+1]; char buf[MAXPATHLEN+1];
Py_UNICODE *u, *p; Py_UNICODE *u, *p;
Py_ssize_t len; Py_ssize_t len;
@ -253,6 +254,11 @@ _Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent)
break; break;
} }
} }
res = PyObject_CallMethod(fob, "close", "");
if (res)
Py_DECREF(res);
else
PyErr_Clear();
Py_DECREF(fob); Py_DECREF(fob);
if (!lineobj || !PyUnicode_Check(lineobj)) { if (!lineobj || !PyUnicode_Check(lineobj)) {
Py_XDECREF(lineobj); Py_XDECREF(lineobj);