diff -r 98475e024344 Lib/email/parser.py --- a/Lib/email/parser.py Fri May 30 16:28:00 2014 -0400 +++ b/Lib/email/parser.py Sun Jun 01 13:11:37 2014 +0700 @@ -106,8 +106,10 @@ meaning it parses the entire contents of the file. """ fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape') - with fp: + try: return self.parser.parse(fp, headersonly) + finally: + fp.detach() def parsebytes(self, text, headersonly=False): diff -r 98475e024344 Lib/test/test_email/test_email.py --- a/Lib/test/test_email/test_email.py Fri May 30 16:28:00 2014 -0400 +++ b/Lib/test/test_email/test_email.py Sun Jun 01 13:11:37 2014 +0700 @@ -7,6 +7,7 @@ import base64 import unittest import textwrap +import os from io import StringIO, BytesIO from itertools import chain @@ -3390,6 +3391,31 @@ self.assertIsInstance(msg.get_payload(), str) self.assertIsInstance(msg.get_payload(decode=True), bytes) + def test_bytes_parser_does_not_close_file(self): + with openfile('msg_02.txt', 'rb') as fp: + email.parser.BytesParser().parse(fp) + self.assertFalse(fp.closed) + + def test_bytes_parser_on_exception_does_not_close_file(self): + with openfile('..' + os.path.sep + 'test_email.py', 'rb') as fp: + bytesParser = email.parser.BytesParser + self.assertRaises(email.errors.MissingHeaderBodySeparatorDefect, + bytesParser(policy=email.policy.strict).parse, + fp) + self.assertFalse(fp.closed) + + def test_parser_does_not_close_file(self): + with openfile('msg_02.txt', 'r') as fp: + email.parser.Parser().parse(fp) + self.assertFalse(fp.closed) + + def test_parser_on_exception_does_not_close_file(self): + with openfile('..' + os.path.sep + 'test_email.py', 'r') as fp: + parser = email.parser.Parser + self.assertRaises(email.errors.MissingHeaderBodySeparatorDefect, + parser(policy=email.policy.strict).parse, fp) + self.assertFalse(fp.closed) + def test_whitespace_continuation(self): eq = self.assertEqual # This message contains a line after the Subject: header that has only