diff -r b1e99b4ec374 Lib/email/parser.py --- a/Lib/email/parser.py Sat Jun 07 23:18:12 2014 -0700 +++ b/Lib/email/parser.py Sun Jun 08 23:16:41 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 b1e99b4ec374 Lib/test/test_email/test_email.py --- a/Lib/test/test_email/test_email.py Sat Jun 07 23:18:12 2014 -0700 +++ b/Lib/test/test_email/test_email.py Sun Jun 08 23:16:41 2014 +0700 @@ -3390,6 +3390,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('msg_15.txt', 'rb') as fp: + bytesParser = email.parser.BytesParser + self.assertRaises(email.errors.StartBoundaryNotFoundDefect, + 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('msg_15.txt', 'r') as fp: + parser = email.parser.Parser + self.assertRaises(email.errors.StartBoundaryNotFoundDefect, + 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