diff -r fc7dbba57869 Doc/includes/email-mime.py --- a/Doc/includes/email-mime.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Doc/includes/email-mime.py Fri Mar 20 09:17:09 2015 +0000 @@ -20,9 +20,8 @@ msg.preamble = 'Our family reunion' for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. - fp = open(file, 'rb') + with open(file, 'rb') as fp: img = MIMEImage(fp.read()) - fp.close() msg.attach(img) # Send the email via our own SMTP server. diff -r fc7dbba57869 Doc/includes/email-simple.py --- a/Doc/includes/email-simple.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Doc/includes/email-simple.py Fri Mar 20 09:17:09 2015 +0000 @@ -6,10 +6,9 @@ from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. -fp = open(textfile, 'rb') +with open(textfile, 'rb') as fp: # Create a text/plain message msg = MIMEText(fp.read()) -fp.close() # me == the sender's email address # you == the recipient's email address diff -r fc7dbba57869 Lib/binhex.py --- a/Lib/binhex.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/binhex.py Fri Mar 20 09:17:09 2015 +0000 @@ -229,14 +229,13 @@ def binhex(inp, out): finfo = getfileinfo(inp) ofp = BinHex(finfo, out) - ifp = io.open(inp, 'rb') + with io.open(inp, 'rb') as ifp: # XXXX Do textfile translation on non-mac systems while True: d = ifp.read(128000) if not d: break ofp.write(d) ofp.close_data() - ifp.close() ifp = openrsrc(inp, 'rb') while True: @@ -449,13 +448,12 @@ def hexbin(inp, out): if not out: out = ifp.FName - ofp = io.open(out, 'wb') + with io.open(out, 'wb') as ofp: # XXXX Do translation on non-mac systems while True: d = ifp.read(128000) if not d: break ofp.write(d) - ofp.close() ifp.close_data() d = ifp.read_rsrc(128000) diff -r fc7dbba57869 Lib/cgitb.py --- a/Lib/cgitb.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/cgitb.py Fri Mar 20 09:17:09 2015 +0000 @@ -294,9 +294,8 @@ class Hook: (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir) try: - file = os.fdopen(fd, 'w') + with os.fdopen(fd, 'w') as file: file.write(doc) - file.close() msg = '%s contains the description of this error.' % path except: msg = 'Tried to save traceback to %s, but failed.' % path diff -r fc7dbba57869 Lib/dbm/__init__.py --- a/Lib/dbm/__init__.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/dbm/__init__.py Fri Mar 20 09:17:09 2015 +0000 @@ -153,9 +153,9 @@ def whichdb(filename): except OSError: return None + with f: # Read the start of the file -- the magic number s16 = f.read(16) - f.close() s = s16[0:4] # Return "" if not at least 4 bytes diff -r fc7dbba57869 Lib/distutils/archive_util.py --- a/Lib/distutils/archive_util.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/distutils/archive_util.py Fri Mar 20 09:17:09 2015 +0000 @@ -164,13 +164,13 @@ def make_zipfile(base_name, base_dir, ve zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED) + with zip: for dirpath, dirnames, filenames in os.walk(base_dir): for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) log.info("adding '%s'" % path) - zip.close() return zip_filename diff -r fc7dbba57869 Lib/distutils/command/bdist_msi.py --- a/Lib/distutils/command/bdist_msi.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/distutils/command/bdist_msi.py Fri Mar 20 09:17:09 2015 +0000 @@ -390,7 +390,7 @@ class bdist_msi(Command): # entries for each version as the above code does if self.pre_install_script: scriptfn = os.path.join(self.bdist_dir, "preinstall.bat") - f = open(scriptfn, "w") + with open(scriptfn, "w") as f: # The batch file will be executed with [PYTHON], so that %1 # is the path to the Python interpreter; %0 will be the path # of the batch file. @@ -400,8 +400,8 @@ class bdist_msi(Command): # """ # f.write('rem ="""\n%1 %0\nexit\n"""\n') - f.write(open(self.pre_install_script).read()) - f.close() + with open(self.pre_install_script) as fin: + f.write(fin.read()) add_data(self.db, "Binary", [("PreInstall", msilib.Binary(scriptfn)) ]) diff -r fc7dbba57869 Lib/distutils/command/config.py --- a/Lib/distutils/command/config.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/distutils/command/config.py Fri Mar 20 09:17:09 2015 +0000 @@ -106,7 +106,7 @@ class config(Command): def _gen_temp_sourcefile(self, body, headers, lang): filename = "_configtest" + LANG_EXT[lang] - file = open(filename, "w") + with open(filename, "w") as file: if headers: for header in headers: file.write("#include <%s>\n" % header) @@ -114,7 +114,6 @@ class config(Command): file.write(body) if body[-1] != "\n": file.write("\n") - file.close() return filename def _preprocess(self, body, headers, include_dirs, lang): @@ -203,7 +202,7 @@ class config(Command): if isinstance(pattern, str): pattern = re.compile(pattern) - file = open(out) + with open(out) as file: match = False while True: line = file.readline() @@ -213,7 +212,6 @@ class config(Command): match = True break - file.close() self._clean() return match diff -r fc7dbba57869 Lib/distutils/command/sdist.py --- a/Lib/distutils/command/sdist.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/distutils/command/sdist.py Fri Mar 20 09:17:09 2015 +0000 @@ -379,14 +379,13 @@ class sdist(Command): distribution. """ log.info("reading manifest file '%s'", self.manifest) - manifest = open(self.manifest) + with open(self.manifest) as manifest: for line in manifest: # ignore comments and blank lines line = line.strip() if line.startswith('#') or not line: continue self.filelist.append(line) - manifest.close() def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source diff -r fc7dbba57869 Lib/distutils/util.py --- a/Lib/distutils/util.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/distutils/util.py Fri Mar 20 09:17:09 2015 +0000 @@ -383,6 +383,7 @@ def byte_compile (py_files, else: script = open(script_name, "w") + with script: script.write("""\ from distutils.util import byte_compile files = [ @@ -410,8 +411,6 @@ byte_compile(files, optimize=%r, force=% direct=1) """ % (optimize, force, prefix, base_dir, verbose)) - script.close() - cmd = [sys.executable, script_name] if optimize == 1: cmd.insert(1, "-O") diff -r fc7dbba57869 Lib/http/cookiejar.py --- a/Lib/http/cookiejar.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/http/cookiejar.py Fri Mar 20 09:17:09 2015 +0000 @@ -1983,7 +1983,6 @@ class MozillaCookieJar(FileCookieJar): magic = f.readline() if not self.magic_re.search(magic): - f.close() raise LoadError( "%r does not look like a Netscape format cookies file" % filename) diff -r fc7dbba57869 Lib/platform.py --- a/Lib/platform.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/platform.py Fri Mar 20 09:17:09 2015 +0000 @@ -163,7 +163,7 @@ def libc_ver(executable=sys.executable, # here to work around problems with Cygwin not being # able to open symlinks for reading executable = os.path.realpath(executable) - f = open(executable, 'rb') + with open(executable, 'rb') as f: binary = f.read(chunksize) pos = 0 while 1: @@ -196,7 +196,6 @@ def libc_ver(executable=sys.executable, if threads and version[-len(threads):] != threads: version = version + threads pos = m.end() - f.close() return lib, version def _dist_try_harder(distname, version, id): diff -r fc7dbba57869 Lib/pydoc.py --- a/Lib/pydoc.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/pydoc.py Fri Mar 20 09:17:09 2015 +0000 @@ -1614,9 +1614,8 @@ def writedoc(thing, forceload=0): try: object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) - file = open(name + '.html', 'w', encoding='utf-8') + with open(name + '.html', 'w', encoding='utf-8') as file: file.write(page) - file.close() print('wrote', name + '.html') except (ImportError, ErrorDuringImport) as value: print(value) diff -r fc7dbba57869 Lib/sre_constants.py --- a/Lib/sre_constants.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/sre_constants.py Fri Mar 20 09:17:09 2015 +0000 @@ -166,7 +166,7 @@ if __name__ == "__main__": items = sorted(d) for item in items: f.write("#define %s_%s %d\n" % (prefix, item, item)) - f = open("sre_constants.h", "w") + with open("sre_constants.h", "w") as f: f.write("""\ /* * Secret Labs' Regular Expression Engine @@ -203,5 +203,4 @@ if __name__ == "__main__": f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL) f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET) - f.close() print("done") diff -r fc7dbba57869 Lib/test/script_helper.py --- a/Lib/test/script_helper.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/script_helper.py Fri Mar 20 09:17:09 2015 +0000 @@ -115,16 +115,15 @@ def make_script(script_dir, script_basen script_filename += os.extsep + 'py' script_name = os.path.join(script_dir, script_filename) # The script should be encoded to UTF-8, the default string encoding - script_file = open(script_name, 'w', encoding='utf-8') + with open(script_name, 'w', encoding='utf-8') as script_file: script_file.write(source) - script_file.close() importlib.invalidate_caches() return script_name def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None): zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) - zip_file = zipfile.ZipFile(zip_name, 'w') + with zipfile.ZipFile(zip_name, 'w') as zip_file: if name_in_zip is None: parts = script_name.split(os.sep) if len(parts) >= 2 and parts[-2] == '__pycache__': @@ -134,12 +133,10 @@ def make_zip_script(zip_dir, zip_basenam else: name_in_zip = os.path.basename(script_name) zip_file.write(script_name, name_in_zip) - zip_file.close() #if test.support.verbose: - # zip_file = zipfile.ZipFile(zip_name, 'r') + # with zipfile.ZipFile(zip_name, 'r') as zip_file: # print 'Contents of %r:' % zip_name # zip_file.printdir() - # zip_file.close() return zip_name, os.path.join(zip_name, name_in_zip) def make_pkg(pkg_dir, init_source=''): @@ -162,17 +159,15 @@ def make_zip_pkg(zip_dir, zip_basename, script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name)) zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) - zip_file = zipfile.ZipFile(zip_name, 'w') + with zipfile.ZipFile(zip_name, 'w') as zip_file: for name in pkg_names: init_name_in_zip = os.path.join(name, init_basename) zip_file.write(init_name, init_name_in_zip) zip_file.write(script_name, script_name_in_zip) - zip_file.close() for name in unlink: os.unlink(name) #if test.support.verbose: - # zip_file = zipfile.ZipFile(zip_name, 'r') + # with zipfile.ZipFile(zip_name, 'r') as zip_file: # print 'Contents of %r:' % zip_name # zip_file.printdir() - # zip_file.close() return zip_name, os.path.join(zip_name, script_name_in_zip) diff -r fc7dbba57869 Lib/test/support/__init__.py --- a/Lib/test/support/__init__.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/support/__init__.py Fri Mar 20 09:17:09 2015 +0000 @@ -631,9 +631,8 @@ def find_unused_port(family=socket.AF_IN issue if/when we come across it. """ - tempsock = socket.socket(family, socktype) + with socket.socket(family, socktype) as tempsock: port = bind_port(tempsock) - tempsock.close() del tempsock return port @@ -1575,10 +1574,11 @@ class _MemoryWatchdog: sys.stderr.flush() return + with f: watchdog_script = findfile("memory_watchdog.py") self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script], - stdin=f, stderr=subprocess.DEVNULL) - f.close() + stdin=f, + stderr=subprocess.DEVNULL) self.started = True def stop(self): diff -r fc7dbba57869 Lib/test/test_argparse.py --- a/Lib/test/test_argparse.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_argparse.py Fri Mar 20 09:17:09 2015 +0000 @@ -1349,9 +1349,8 @@ class TestArgumentsFromFile(TempDirMixin ('invalid', '@no-such-path\n'), ] for path, text in file_texts: - file = open(path, 'w') + with open(path, 'w') as file: file.write(text) - file.close() parser_signature = Sig(fromfile_prefix_chars='@') argument_signatures = [ @@ -1380,9 +1379,8 @@ class TestArgumentsFromFileConverter(Tem ('hello', 'hello world!\n'), ] for path, text in file_texts: - file = open(path, 'w') + with open(path, 'w') as file: file.write(text) - file.close() class FromFileConverterArgumentParser(ErrorRaisingArgumentParser): @@ -1453,9 +1451,8 @@ class TestFileTypeR(TempDirMixin, Parser def setUp(self): super(TestFileTypeR, self).setUp() for file_name in ['foo', 'bar']: - file = open(os.path.join(self.temp_dir, file_name), 'w') + with open(os.path.join(self.temp_dir, file_name), 'w') as file: file.write(file_name) - file.close() self.create_readonly_file('readonly') argument_signatures = [ @@ -1494,9 +1491,8 @@ class TestFileTypeRB(TempDirMixin, Parse def setUp(self): super(TestFileTypeRB, self).setUp() for file_name in ['foo', 'bar']: - file = open(os.path.join(self.temp_dir, file_name), 'w') + with open(os.path.join(self.temp_dir, file_name), 'w') as file: file.write(file_name) - file.close() argument_signatures = [ Sig('-x', type=argparse.FileType('rb')), diff -r fc7dbba57869 Lib/test/test_binhex.py --- a/Lib/test/test_binhex.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_binhex.py Fri Mar 20 09:17:09 2015 +0000 @@ -24,17 +24,15 @@ class BinHexTestCase(unittest.TestCase): DATA = b'Jack is my hero' def test_binhex(self): - f = open(self.fname1, 'wb') + with open(self.fname1, 'wb') as f: f.write(self.DATA) - f.close() binhex.binhex(self.fname1, self.fname2) binhex.hexbin(self.fname2, self.fname1) - f = open(self.fname1, 'rb') + with open(self.fname1, 'rb') as f: finish = f.readline() - f.close() self.assertEqual(self.DATA, finish) diff -r fc7dbba57869 Lib/test/test_bool.py --- a/Lib/test/test_bool.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_bool.py Fri Mar 20 09:17:09 2015 +0000 @@ -20,13 +20,11 @@ class BoolTest(unittest.TestCase): def test_print(self): try: - fo = open(support.TESTFN, "w") + with open(support.TESTFN, "w") as fo: print(False, True, file=fo) - fo.close() - fo = open(support.TESTFN, "r") - self.assertEqual(fo.read(), 'False True\n') + with open(support.TESTFN, "r") as fi: + self.assertEqual(fi.read(), 'False True\n') finally: - fo.close() os.remove(support.TESTFN) def test_repr(self): @@ -234,9 +232,8 @@ class BoolTest(unittest.TestCase): def test_fileclosed(self): try: - f = open(support.TESTFN, "w") + with open(support.TESTFN, "w") as f: self.assertIs(f.closed, False) - f.close() self.assertIs(f.closed, True) finally: os.remove(support.TESTFN) diff -r fc7dbba57869 Lib/test/test_codecs.py --- a/Lib/test/test_codecs.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_codecs.py Fri Mar 20 09:17:09 2015 +0000 @@ -1129,9 +1129,8 @@ class EscapeDecodeTest(unittest.TestCase class RecodingTest(unittest.TestCase): def test_recoding(self): f = io.BytesIO() - f2 = codecs.EncodedFile(f, "unicode_internal", "utf-8") + with codecs.EncodedFile(f, "unicode_internal", "utf-8") as f2: f2.write("a") - f2.close() # Python used to crash on this at exit because of a refcount # bug in _codecsmodule.c diff -r fc7dbba57869 Lib/test/test_curses.py --- a/Lib/test/test_curses.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_curses.py Fri Mar 20 09:17:09 2015 +0000 @@ -184,11 +184,10 @@ class TestCurses(unittest.TestCase): curses.delay_output(1) curses.echo() ; curses.echo(1) - f = tempfile.TemporaryFile() + with tempfile.TemporaryFile() as f: stdscr.putwin(f) f.seek(0) curses.getwin(f) - f.close() curses.halfdelay(1) curses.intrflush(1) diff -r fc7dbba57869 Lib/test/test_dbm_dumb.py --- a/Lib/test/test_dbm_dumb.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_dbm_dumb.py Fri Mar 20 09:17:09 2015 +0000 @@ -2,6 +2,7 @@ Original by Roger E. Masse """ +import contextlib import io import operator import os @@ -31,12 +32,11 @@ class DumbDBMTestCase(unittest.TestCase) } def test_dumbdbm_creation(self): - f = dumbdbm.open(_fname, 'c') + with contextlib.closing(dumbdbm.open(_fname, 'c')) as f: self.assertEqual(list(f.keys()), []) for key in self._dict: f[key] = self._dict[key] self.read_helper(f) - f.close() @unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()') @unittest.skipUnless(hasattr(os, 'chmod'), 'test needs os.chmod()') @@ -69,51 +69,44 @@ class DumbDBMTestCase(unittest.TestCase) def test_dumbdbm_modification(self): self.init_db() - f = dumbdbm.open(_fname, 'w') + with contextlib.closing(dumbdbm.open(_fname, 'w')) as f: self._dict[b'g'] = f[b'g'] = b"indented" self.read_helper(f) - f.close() def test_dumbdbm_read(self): self.init_db() - f = dumbdbm.open(_fname, 'r') + with contextlib.closing(dumbdbm.open(_fname, 'r')) as f: self.read_helper(f) - f.close() def test_dumbdbm_keys(self): self.init_db() - f = dumbdbm.open(_fname) + with contextlib.closing(dumbdbm.open(_fname)) as f: keys = self.keys_helper(f) - f.close() def test_write_contains(self): - f = dumbdbm.open(_fname) + with contextlib.closing(dumbdbm.open(_fname)) as f: f[b'1'] = b'hello' self.assertIn(b'1', f) - f.close() def test_write_write_read(self): # test for bug #482460 - f = dumbdbm.open(_fname) + with contextlib.closing(dumbdbm.open(_fname)) as f: f[b'1'] = b'hello' f[b'1'] = b'hello2' - f.close() - f = dumbdbm.open(_fname) + with contextlib.closing(dumbdbm.open(_fname)) as f: self.assertEqual(f[b'1'], b'hello2') - f.close() def test_str_read(self): self.init_db() - f = dumbdbm.open(_fname, 'r') + with contextlib.closing(dumbdbm.open(_fname, 'r')) as f: self.assertEqual(f['\u00fc'], self._dict['\u00fc'.encode('utf-8')]) def test_str_write_contains(self): self.init_db() - f = dumbdbm.open(_fname) + with contextlib.closing(dumbdbm.open(_fname)) as f: f['\u00fc'] = b'!' f['1'] = 'a' - f.close() - f = dumbdbm.open(_fname, 'r') + with contextlib.closing(dumbdbm.open(_fname, 'r')) as f: self.assertIn('\u00fc', f) self.assertEqual(f['\u00fc'.encode('utf-8')], self._dict['\u00fc'.encode('utf-8')]) @@ -122,10 +115,9 @@ class DumbDBMTestCase(unittest.TestCase) def test_line_endings(self): # test for bug #1172763: dumbdbm would die if the line endings # weren't what was expected. - f = dumbdbm.open(_fname) + with contextlib.closing(dumbdbm.open(_fname)) as f: f[b'1'] = b'hello' f[b'2'] = b'hello2' - f.close() # Mangle the file by changing the line separator to Windows or Unix with io.open(_fname + '.dir', 'rb') as file: @@ -148,10 +140,9 @@ class DumbDBMTestCase(unittest.TestCase) self.assertEqual(self._dict[key], f[key]) def init_db(self): - f = dumbdbm.open(_fname, 'w') + with contextlib.closing(dumbdbm.open(_fname, 'w')) as f: for k in self._dict: f[k] = self._dict[k] - f.close() def keys_helper(self, f): keys = sorted(f.keys()) @@ -165,7 +156,7 @@ class DumbDBMTestCase(unittest.TestCase) import random d = {} # mirror the database for dummy in range(5): - f = dumbdbm.open(_fname) + with contextlib.closing(dumbdbm.open(_fname)) as f: for dummy in range(100): k = random.choice('abcdefghijklm') if random.random() < 0.2: @@ -177,13 +168,11 @@ class DumbDBMTestCase(unittest.TestCase) d[k] = v f[k] = v self.assertEqual(f[k], v) - f.close() - f = dumbdbm.open(_fname) + with contextlib.closing(dumbdbm.open(_fname)) as f: expected = sorted((k.encode("latin-1"), v) for k, v in d.items()) got = sorted(f.items()) self.assertEqual(expected, got) - f.close() def test_context_manager(self): with dumbdbm.open(_fname, 'c') as db: diff -r fc7dbba57869 Lib/test/test_epoll.py --- a/Lib/test/test_epoll.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_epoll.py Fri Mar 20 09:17:09 2015 +0000 @@ -135,7 +135,7 @@ class TestEPoll(unittest.TestCase): def test_fromfd(self): server, client = self._connected_pair() - ep = select.epoll(2) + with select.epoll(2) as ep: ep2 = select.epoll.fromfd(ep.fileno()) ep2.register(server.fileno(), select.EPOLLIN | select.EPOLLOUT) @@ -146,7 +146,6 @@ class TestEPoll(unittest.TestCase): self.assertEqual(len(events), 2) self.assertEqual(len(events2), 2) - ep.close() try: ep2.poll(1, 4) except OSError as e: diff -r fc7dbba57869 Lib/test/test_float.py --- a/Lib/test/test_float.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_float.py Fri Mar 20 09:17:09 2015 +0000 @@ -599,15 +599,14 @@ class FormatTestCase(unittest.TestCase): class ReprTestCase(unittest.TestCase): def test_repr(self): - floats_file = open(os.path.join(os.path.split(__file__)[0], - 'floating_points.txt')) + with open(os.path.join(os.path.split(__file__)[0], + 'floating_points.txt')) as floats_file: for line in floats_file: line = line.strip() if not line or line.startswith('#'): continue v = eval(line) self.assertEqual(v, eval(repr(v))) - floats_file.close() @unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short', "applies only when using short float repr style") diff -r fc7dbba57869 Lib/test/test_ioctl.py --- a/Lib/test/test_ioctl.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_ioctl.py Fri Mar 20 09:17:09 2015 +0000 @@ -11,9 +11,9 @@ try: except OSError: raise unittest.SkipTest("Unable to open /dev/tty") else: + with tty: # Skip if another process is in foreground r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") - tty.close() rpgrp = struct.unpack("i", r)[0] if rpgrp not in (os.getpgrp(), os.getsid(0)): raise unittest.SkipTest("Neither the process group nor the session " diff -r fc7dbba57869 Lib/test/test_mmap.py --- a/Lib/test/test_mmap.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_mmap.py Fri Mar 20 09:17:09 2015 +0000 @@ -268,13 +268,12 @@ class MmapTests(unittest.TestCase): def test_find_end(self): # test the new 'end' parameter works as expected - f = open(TESTFN, 'wb+') + with open(TESTFN, 'wb+') as f: data = b'one two ones' n = len(data) f.write(data) f.flush() m = mmap.mmap(f.fileno(), n) - f.close() self.assertEqual(m.find(b'one'), 0) self.assertEqual(m.find(b'ones'), 8) @@ -286,13 +285,12 @@ class MmapTests(unittest.TestCase): def test_rfind(self): # test the new 'end' parameter works as expected - f = open(TESTFN, 'wb+') + with open(TESTFN, 'wb+') as f: data = b'one two ones' n = len(data) f.write(data) f.flush() m = mmap.mmap(f.fileno(), n) - f.close() self.assertEqual(m.rfind(b'one'), 8) self.assertEqual(m.rfind(b'one '), 0) @@ -304,31 +302,24 @@ class MmapTests(unittest.TestCase): def test_double_close(self): # make sure a double close doesn't crash on Solaris (Bug# 665913) - f = open(TESTFN, 'wb+') + with open(TESTFN, 'wb+') as f: + f.write(2**16 * b'a') # Arbitrary character - f.write(2**16 * b'a') # Arbitrary character - f.close() - - f = open(TESTFN, 'rb') + with open(TESTFN, 'rb') as f: mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ) mf.close() mf.close() - f.close() @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()") def test_entire_file(self): # test mapping of entire file by passing 0 for map length - f = open(TESTFN, "wb+") + with open(TESTFN, "wb+") as f: + f.write(2**16 * b'm') # Arbitrary character - f.write(2**16 * b'm') # Arbitrary character - f.close() - - f = open(TESTFN, "rb+") - mf = mmap.mmap(f.fileno(), 0) + with open(TESTFN, "rb+") as f, \ + mmap.mmap(f.fileno(), 0) as mf: self.assertEqual(len(mf), 2**16, "Map size should equal file size.") self.assertEqual(mf.read(2**16), 2**16 * b"m") - mf.close() - f.close() @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()") def test_length_0_offset(self): @@ -356,7 +347,7 @@ class MmapTests(unittest.TestCase): def test_move(self): # make move works everywhere (64-bit format problem earlier) - f = open(TESTFN, 'wb+') + with open(TESTFN, 'wb+') as f: f.write(b"ABCDEabcde") # Arbitrary character f.flush() @@ -365,7 +356,6 @@ class MmapTests(unittest.TestCase): mf.move(5, 0, 5) self.assertEqual(mf[:], b"ABCDEABCDE", "Map move should have duplicated front 5") mf.close() - f.close() # more excessive test data = b"0123456789" @@ -563,10 +553,9 @@ class MmapTests(unittest.TestCase): mapsize = 10 with open(TESTFN, "wb") as fp: fp.write(b"a"*mapsize) - f = open(TESTFN, "rb") + with open(TESTFN, "rb") as f: m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ) self.assertRaises(TypeError, m.write, "foo") - f.close() def test_error(self): self.assertIs(mmap.error, OSError) @@ -575,9 +564,8 @@ class MmapTests(unittest.TestCase): data = b"0123456789" with open(TESTFN, "wb") as fp: fp.write(b"x"*len(data)) - f = open(TESTFN, "r+b") + with open(TESTFN, "r+b") as f: m = mmap.mmap(f.fileno(), len(data)) - f.close() # Test write_byte() for i in range(len(data)): self.assertEqual(m.tell(), i) diff -r fc7dbba57869 Lib/test/test_os.py --- a/Lib/test/test_os.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_os.py Fri Mar 20 09:17:09 2015 +0000 @@ -205,9 +205,8 @@ class StatAttributeTests(unittest.TestCa def setUp(self): os.mkdir(support.TESTFN) self.fname = os.path.join(support.TESTFN, "f1") - f = open(self.fname, 'wb') + with open(self.fname, 'wb') as f: f.write(b"ABC") - f.close() def tearDown(self): os.unlink(self.fname) @@ -772,9 +771,8 @@ class WalkTests(unittest.TestCase): os.makedirs(sub2_path) os.makedirs(t2_path) for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path: - f = open(path, "w") + with open(path, "w") as f: f.write("I'm " + path + " and proud of it. Blame test_os.\n") - f.close() if support.can_symlink(): os.symlink(os.path.abspath(t2_path), link_path) os.symlink('broken', broken_link_path, True) @@ -996,9 +994,8 @@ class MakedirTests(unittest.TestCase): def test_exist_ok_existing_regular_file(self): base = support.TESTFN path = os.path.join(support.TESTFN, 'dir1') - f = open(path, 'w') + with open(path, 'w') as f: f.write('abc') - f.close() self.assertRaises(OSError, os.makedirs, path) self.assertRaises(OSError, os.makedirs, path, exist_ok=False) self.assertRaises(OSError, os.makedirs, path, exist_ok=True) diff -r fc7dbba57869 Lib/test/test_pipes.py --- a/Lib/test/test_pipes.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_pipes.py Fri Mar 20 09:17:09 2015 +0000 @@ -20,9 +20,8 @@ class SimplePipeTests(unittest.TestCase) def testSimplePipe1(self): t = pipes.Template() t.append(s_command, pipes.STDIN_STDOUT) - f = t.open(TESTFN, 'w') + with t.open(TESTFN, 'w') as f: f.write('hello world #1') - f.close() with open(TESTFN) as f: self.assertEqual(f.read(), 'HELLO WORLD #1') diff -r fc7dbba57869 Lib/test/test_pkg.py --- a/Lib/test/test_pkg.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_pkg.py Fri Mar 20 09:17:09 2015 +0000 @@ -81,11 +81,10 @@ class TestPkg(unittest.TestCase): if contents is None: os.mkdir(fullname) else: - f = open(fullname, "w") + with open(fullname, "w") as f: f.write(contents) if contents and contents[-1] != '\n': f.write('\n') - f.close() self.root = root # package name is the name of the first item self.pkgname = descr[0][0] diff -r fc7dbba57869 Lib/test/test_platform.py --- a/Lib/test/test_platform.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_platform.py Fri Mar 20 09:17:09 2015 +0000 @@ -190,13 +190,12 @@ class PlatformTest(unittest.TestCase): if platform.uname().system == 'Darwin': # We're on a MacOSX system, check that # the right version information is returned - fd = os.popen('sw_vers', 'r') + with os.popen('sw_vers', 'r') as fd: real_ver = None for ln in fd: if ln.startswith('ProductVersion:'): real_ver = ln.strip().split()[-1] break - fd.close() self.assertFalse(real_ver is None) result_list = res[0].split('.') expect_list = real_ver.split('.') diff -r fc7dbba57869 Lib/test/test_poll.py --- a/Lib/test/test_poll.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_poll.py Fri Mar 20 09:17:09 2015 +0000 @@ -86,13 +86,12 @@ class PollTests(unittest.TestCase): r = p.poll() self.assertEqual(r[0], (FD, select.POLLNVAL)) - f = open(TESTFN, 'w') + with open(TESTFN, 'w') as f: fd = f.fileno() p = select.poll() p.register(f) r = p.poll() self.assertEqual(r[0][0], fd) - f.close() r = p.poll() self.assertEqual(r[0], (fd, select.POLLNVAL)) os.unlink(TESTFN) diff -r fc7dbba57869 Lib/test/test_random.py --- a/Lib/test/test_random.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_random.py Fri Mar 20 09:17:09 2015 +0000 @@ -173,9 +173,8 @@ class TestBasicOps: ("randv2_64.pck", 866), ("randv3.pck", 343)] for file, value in files: - f = open(support.findfile(file),"rb") + with open(support.findfile(file),"rb") as f: r = pickle.load(f) - f.close() self.assertEqual(int(r.random()*1000), value) def test_bug_9025(self): diff -r fc7dbba57869 Lib/test/test_runpy.py --- a/Lib/test/test_runpy.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_runpy.py Fri Mar 20 09:17:09 2015 +0000 @@ -234,9 +234,8 @@ class RunModuleTestCase(unittest.TestCas if verbose > 1: print(" Next level in:", sub_dir) if verbose > 1: print(" Created:", pkg_fname) mod_fname = os.path.join(sub_dir, test_fname) - mod_file = open(mod_fname, "w") + with open(mod_fname, "w") as mod_file: mod_file.write(source) - mod_file.close() if verbose > 1: print(" Created:", mod_fname) mod_name = (pkg_name+".")*depth + mod_base mod_spec = importlib.util.spec_from_file_location(mod_name, diff -r fc7dbba57869 Lib/test/test_select.py --- a/Lib/test/test_select.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_select.py Fri Mar 20 09:17:09 2015 +0000 @@ -46,7 +46,7 @@ class SelectTestCase(unittest.TestCase): def test_select(self): cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' - p = os.popen(cmd, 'r') + with os.popen(cmd, 'r') as p: for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: if support.verbose: print('timeout =', tout) @@ -63,7 +63,6 @@ class SelectTestCase(unittest.TestCase): break continue self.fail('Unexpected return values from select():', rfd, wfd, xfd) - p.close() # Issue 16230: Crash on select resized list def test_select_mutated(self): diff -r fc7dbba57869 Lib/test/test_shelve.py --- a/Lib/test/test_shelve.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_shelve.py Fri Mar 20 09:17:09 2015 +0000 @@ -88,15 +88,13 @@ class TestCase(unittest.TestCase): def test_in_memory_shelf(self): d1 = byteskeydict() - s = shelve.Shelf(d1, protocol=0) + with shelve.Shelf(d1, protocol=0) as s: s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) - s.close() d2 = byteskeydict() - s = shelve.Shelf(d2, protocol=1) + with shelve.Shelf(d2, protocol=1) as s: s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) - s.close() self.assertEqual(len(d1), 1) self.assertEqual(len(d2), 1) @@ -104,20 +102,18 @@ class TestCase(unittest.TestCase): def test_mutable_entry(self): d1 = byteskeydict() - s = shelve.Shelf(d1, protocol=2, writeback=False) + with shelve.Shelf(d1, protocol=2, writeback=False) as s: s['key1'] = [1,2,3,4] self.assertEqual(s['key1'], [1,2,3,4]) s['key1'].append(5) self.assertEqual(s['key1'], [1,2,3,4]) - s.close() d2 = byteskeydict() - s = shelve.Shelf(d2, protocol=2, writeback=True) + with shelve.Shelf(d2, protocol=2, writeback=True) as s: s['key1'] = [1,2,3,4] self.assertEqual(s['key1'], [1,2,3,4]) s['key1'].append(5) self.assertEqual(s['key1'], [1,2,3,4,5]) - s.close() self.assertEqual(len(d1), 1) self.assertEqual(len(d2), 1) @@ -140,11 +136,10 @@ class TestCase(unittest.TestCase): d = {} key = 'key' encodedkey = key.encode('utf-8') - s = shelve.Shelf(d, writeback=True) + with shelve.Shelf(d, writeback=True) as s: s[key] = [1] p1 = d[encodedkey] # Will give a KeyError if backing store not updated s['key'].append(2) - s.close() p2 = d[encodedkey] self.assertNotEqual(p1, p2) # Write creates new object in store diff -r fc7dbba57869 Lib/test/test_site.py --- a/Lib/test/test_site.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_site.py Fri Mar 20 09:17:09 2015 +0000 @@ -102,10 +102,9 @@ class HelperFunctionsTests(unittest.Test pth_dir = os.path.abspath(pth_dir) pth_basename = pth_name + '.pth' pth_fn = os.path.join(pth_dir, pth_basename) - pth_file = open(pth_fn, 'w', encoding='utf-8') + with open(pth_fn, 'w', encoding='utf-8') as pth_file: self.addCleanup(lambda: os.remove(pth_fn)) pth_file.write(contents) - pth_file.close() return pth_dir, pth_basename def test_addpackage_import_bad_syntax(self): diff -r fc7dbba57869 Lib/test/test_socket.py --- a/Lib/test/test_socket.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_socket.py Fri Mar 20 09:17:09 2015 +0000 @@ -686,10 +686,9 @@ class GeneralModuleTests(unittest.TestCa self.assertEqual(repr(s), expected) def test_weakref(self): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: p = proxy(s) self.assertEqual(p.fileno(), s.fileno()) - s.close() s = None try: p.fileno() @@ -933,23 +932,20 @@ class GeneralModuleTests(unittest.TestCa # Testing default timeout # The default timeout should initially be None self.assertEqual(socket.getdefaulttimeout(), None) - s = socket.socket() + with socket.socket() as s: self.assertEqual(s.gettimeout(), None) - s.close() # Set the default timeout to 10, and see if it propagates socket.setdefaulttimeout(10) self.assertEqual(socket.getdefaulttimeout(), 10) - s = socket.socket() + with socket.socket() as s: self.assertEqual(s.gettimeout(), 10) - s.close() # Reset the default timeout to None, and see if it propagates socket.setdefaulttimeout(None) self.assertEqual(socket.getdefaulttimeout(), None) - s = socket.socket() + with socket.socket() as s: self.assertEqual(s.gettimeout(), None) - s.close() # Check that setting it to an invalid value raises ValueError self.assertRaises(ValueError, socket.setdefaulttimeout, -1) @@ -1153,15 +1149,14 @@ class GeneralModuleTests(unittest.TestCa def testSendAfterClose(self): # testing send() after close() with timeout - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.settimeout(1) - sock.close() self.assertRaises(OSError, sock.send, b"spam") def testNewAttributes(self): # testing .family, .type and .protocol - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: self.assertEqual(sock.family, socket.AF_INET) if hasattr(socket, 'SOCK_CLOEXEC'): self.assertIn(sock.type, @@ -1170,7 +1165,6 @@ class GeneralModuleTests(unittest.TestCa else: self.assertEqual(sock.type, socket.SOCK_STREAM) self.assertEqual(sock.proto, 0) - sock.close() def test_getsockaddrarg(self): sock = socket.socket() @@ -1392,10 +1386,9 @@ class GeneralModuleTests(unittest.TestCa def test_listen_backlog_overflow(self): # Issue 15989 import _testcapi - srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: srv.bind((HOST, 0)) self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1) - srv.close() @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') def test_flowinfo(self): diff -r fc7dbba57869 Lib/test/test_socketserver.py --- a/Lib/test/test_socketserver.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_socketserver.py Fri Mar 20 09:17:09 2015 +0000 @@ -148,7 +148,7 @@ class SocketServerTest(unittest.TestCase if verbose: print("done") def stream_examine(self, proto, addr): - s = socket.socket(proto, socket.SOCK_STREAM) + with socket.socket(proto, socket.SOCK_STREAM) as s: s.connect(addr) s.sendall(TEST_STR) buf = data = receive(s, 100) @@ -156,17 +156,15 @@ class SocketServerTest(unittest.TestCase data = receive(s, 100) buf += data self.assertEqual(buf, TEST_STR) - s.close() def dgram_examine(self, proto, addr): - s = socket.socket(proto, socket.SOCK_DGRAM) + with socket.socket(proto, socket.SOCK_DGRAM) as s: s.sendto(TEST_STR, addr) buf = data = receive(s, 100) while data and b'\n' not in buf: data = receive(s, 100) buf += data self.assertEqual(buf, TEST_STR) - s.close() def test_TCPServer(self): self.run_server(socketserver.TCPServer, diff -r fc7dbba57869 Lib/test/test_ssl.py --- a/Lib/test/test_ssl.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_ssl.py Fri Mar 20 09:17:09 2015 +0000 @@ -1328,11 +1328,10 @@ class NetworkedTests(unittest.TestCase): s.close() # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) + with ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED) as s: self.assertRaisesRegex(ssl.SSLError, "certificate verify failed", s.connect, ("svn.python.org", 443)) - s.close() # this should succeed because we specify the root cert s = ssl.wrap_socket(socket.socket(socket.AF_INET), diff -r fc7dbba57869 Lib/test/test_tarfile.py --- a/Lib/test/test_tarfile.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_tarfile.py Fri Mar 20 09:17:09 2015 +0000 @@ -127,8 +127,7 @@ class UstarReadTest(ReadTest, unittest.T data = fobj.read() tarinfo = self.tar.getmember("ustar/regtype") - fobj = self.tar.extractfile(tarinfo) - + with self.tar.extractfile(tarinfo) as fobj: text = fobj.read() fobj.seek(0) self.assertEqual(0, fobj.tell(), @@ -169,7 +168,6 @@ class UstarReadTest(ReadTest, unittest.T line = fobj.readline() self.assertEqual(fobj.read(), data[len(line):], "read() after readline() failed") - fobj.close() def test_fileobj_text(self): with self.tar.extractfile("ustar/regtype") as fobj: @@ -437,7 +435,7 @@ class MiscReadTestBase(CommonReadTest): fobj.seek(offset) # Test if the tarfile starts with the second member. - tar = tar.open(self.tarname, mode="r:", fileobj=fobj) + with tar.open(self.tarname, mode="r:", fileobj=fobj) as tar: t = tar.next() self.assertEqual(t.name, name) # Read to the end of fileobj and test if seeking back to the @@ -445,7 +443,6 @@ class MiscReadTestBase(CommonReadTest): tar.getmembers() self.assertEqual(tar.extractfile(t).read(), data, "seek back did not work") - tar.close() def test_fail_comp(self): # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file. @@ -968,9 +965,8 @@ class WriteTestBase(TarTest): def test_fileobj_no_close(self): fobj = io.BytesIO() - tar = tarfile.open(fileobj=fobj, mode=self.mode) + with tarfile.open(fileobj=fobj, mode=self.mode) as tar: tar.addfile(tarfile.TarInfo("foo")) - tar.close() self.assertFalse(fobj.closed, "external fileobjs must never closed") # Issue #20238: Incomplete gzip output with mode="w:gz" data = fobj.getvalue() @@ -1210,10 +1206,9 @@ class WriteTest(WriteTestBase, unittest. with open(source_file,'w') as f: f.write('something\n') os.symlink(source_file, target_file) - tar = tarfile.open(temparchive,'w') + with tarfile.open(temparchive, 'w') as tar: tar.add(source_file) tar.add(target_file) - tar.close() # Let's extract it to the location which contains the symlink tar = tarfile.open(temparchive,'r') # this should not raise OSError: [Errno 17] File exists @@ -1223,6 +1218,12 @@ class WriteTest(WriteTestBase, unittest. self.fail("extractall failed with symlinked files") finally: tar.close() + with tarfile.open(temparchive,'r') as tar: + # this should not raise OSError: [Errno 17] File exists + try: + tar.extractall(path=tempdir) + except OSError: + self.fail("extractall failed with symlinked files") finally: support.unlink(temparchive) support.rmtree(tempdir) diff -r fc7dbba57869 Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_tempfile.py Fri Mar 20 09:17:09 2015 +0000 @@ -466,9 +466,8 @@ class TestGetTempDir(BaseTestCase): # sneaky: just instantiate a NamedTemporaryFile, which # defaults to writing into the directory returned by # gettempdir. - file = tempfile.NamedTemporaryFile() + with tempfile.NamedTemporaryFile() as file: file.write(b"blat") - file.close() def test_same_thing(self): # gettempdir always returns the same object @@ -717,9 +716,8 @@ class TestNamedTemporaryFile(BaseTestCas # A NamedTemporaryFile is deleted when closed dir = tempfile.mkdtemp() try: - f = tempfile.NamedTemporaryFile(dir=dir) + with tempfile.NamedTemporaryFile(dir=dir) as f: f.write(b'blat') - f.close() self.assertFalse(os.path.exists(f.name), "NamedTemporaryFile %s exists after close" % f.name) finally: diff -r fc7dbba57869 Lib/test/test_threading.py --- a/Lib/test/test_threading.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_threading.py Fri Mar 20 09:17:09 2015 +0000 @@ -746,13 +746,11 @@ class ThreadJoinOnShutdown(BaseTestCase) def random_io(): '''Loop for a while sleeping random tiny amounts and doing some I/O.''' while True: - in_f = open(os.__file__, 'rb') + with open(os.__file__, 'rb') as in_f: stuff = in_f.read(200) - null_f = open(os.devnull, 'wb') + with open(os.devnull, 'wb') as null_f: null_f.write(stuff) time.sleep(random.random() / 1995) - null_f.close() - in_f.close() thread_has_run.add(threading.current_thread()) def main(): diff -r fc7dbba57869 Lib/test/test_urllib2.py --- a/Lib/test/test_urllib2.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_urllib2.py Fri Mar 20 09:17:09 2015 +0000 @@ -51,10 +51,8 @@ class TrivialTests(unittest.TestCase): else: file_url = "file://%s" % fname - f = urllib.request.urlopen(file_url) - + with urllib.request.urlopen(file_url) as f: f.read() - f.close() def test_parse_http_list(self): tests = [ diff -r fc7dbba57869 Lib/test/test_urllib2_localnet.py --- a/Lib/test/test_urllib2_localnet.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_urllib2_localnet.py Fri Mar 20 09:17:09 2015 +0000 @@ -361,10 +361,9 @@ class ProxyAuthTests(unittest.TestCase): self.proxy_digest_handler.add_password(self.REALM, self.URL, self.USER, self.PASSWD) self.digest_auth_handler.set_qop("auth") - result = self.opener.open(self.URL) + with self.opener.open(self.URL) as result: while result.read(): pass - result.close() def test_proxy_qop_auth_int_works_or_throws_urlerror(self): self.proxy_digest_handler.add_password(self.REALM, self.URL, @@ -376,11 +375,11 @@ class ProxyAuthTests(unittest.TestCase): # It's okay if we don't support auth-int, but we certainly # shouldn't receive any kind of exception here other than # a URLError. - result = None - if result: + pass + else: + with result: while result.read(): pass - result.close() def GetRequestHandler(responses): @@ -598,14 +597,11 @@ class TestUrlopen(unittest.TestCase): def test_basic(self): handler = self.start_server() - open_url = urllib.request.urlopen("http://localhost:%s" % handler.port) + with urllib.request.urlopen("http://localhost:%s" % handler.port) as open_url: for attr in ("read", "close", "info", "geturl"): self.assertTrue(hasattr(open_url, attr), "object returned from " "urlopen lacks the %s attribute" % attr) - try: self.assertTrue(open_url.read(), "calling 'read' failed") - finally: - open_url.close() def test_info(self): handler = self.start_server() diff -r fc7dbba57869 Lib/test/test_uu.py --- a/Lib/test/test_uu.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_uu.py Fri Mar 20 09:17:09 2015 +0000 @@ -172,26 +172,21 @@ class UUFileTest(unittest.TestCase): fin = fout = None try: support.unlink(self.tmpin) - fin = open(self.tmpin, 'wb') + with open(self.tmpin, 'wb') as fin: fin.write(plaintext) - fin.close() - fin = open(self.tmpin, 'rb') - fout = open(self.tmpout, 'wb') + with open(self.tmpin, 'rb') as fin, \ + open(self.tmpout, 'wb') as fout: uu.encode(fin, fout, self.tmpin, mode=0o644) - fin.close() - fout.close() - fout = open(self.tmpout, 'rb') + with open(self.tmpout, 'rb') as fout: s = fout.read() - fout.close() self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin)) # in_file and out_file as filenames uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644) - fout = open(self.tmpout, 'rb') + with open(self.tmpout, 'rb') as fout: s = fout.read() - fout.close() self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin)) finally: @@ -202,17 +197,14 @@ class UUFileTest(unittest.TestCase): f = None try: support.unlink(self.tmpin) - f = open(self.tmpin, 'wb') + with open(self.tmpin, 'wb') as f: f.write(encodedtextwrapped(0o644, self.tmpout)) - f.close() - f = open(self.tmpin, 'rb') + with open(self.tmpin, 'rb') as f: uu.decode(f) - f.close() - f = open(self.tmpout, 'rb') + with open(self.tmpout, 'rb') as f: s = f.read() - f.close() self.assertEqual(s, plaintext) # XXX is there an xp way to verify the mode? finally: @@ -222,15 +214,13 @@ class UUFileTest(unittest.TestCase): f = None try: support.unlink(self.tmpin) - f = open(self.tmpin, 'wb') + with open(self.tmpin, 'wb') as f: f.write(encodedtextwrapped(0o644, self.tmpout)) - f.close() uu.decode(self.tmpin) - f = open(self.tmpout, 'rb') + with open(self.tmpout, 'rb') as f: s = f.read() - f.close() self.assertEqual(s, plaintext) finally: self._kill(f) @@ -241,13 +231,11 @@ class UUFileTest(unittest.TestCase): try: f = io.BytesIO(encodedtextwrapped(0o644, self.tmpout)) - f = open(self.tmpin, 'rb') + with open(self.tmpin, 'rb') as f: uu.decode(f) - f.close() - f = open(self.tmpin, 'rb') + with open(self.tmpin, 'rb') as f: self.assertRaises(uu.Error, uu.decode, f) - f.close() finally: self._kill(f) diff -r fc7dbba57869 Lib/test/test_xmlrpc.py --- a/Lib/test/test_xmlrpc.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_xmlrpc.py Fri Mar 20 09:17:09 2015 +0000 @@ -586,10 +586,9 @@ class SimpleServerTestCase(BaseServerTes def XXXtest_404(self): # send POST with http.client, it should return 404 header and # 'Not Found' message. - conn = httplib.client.HTTPConnection(ADDR, PORT) + with contextlib.closing(httplib.client.HTTPConnection(ADDR, PORT)) as conn: conn.request('POST', '/this-is-not-valid') response = conn.getresponse() - conn.close() self.assertEqual(response.status, 404) self.assertEqual(response.reason, 'Not Found') @@ -709,9 +708,8 @@ class SimpleServerTestCase(BaseServerTes def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue #14001. - conn = http.client.HTTPConnection(ADDR, PORT) + with contextlib.closing(http.client.HTTPConnection(ADDR, PORT)) as conn: conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye') - conn.close() def test_context_manager(self): with xmlrpclib.ServerProxy(URL) as server: diff -r fc7dbba57869 Lib/test/test_zipfile64.py --- a/Lib/test/test_zipfile64.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_zipfile64.py Fri Mar 20 09:17:09 2015 +0000 @@ -32,18 +32,12 @@ class TestsWithSourceFile(unittest.TestC self.data = '\n'.join(line_gen).encode('ascii') # And write it to a file. - fp = open(TESTFN, "wb") + with open(TESTFN, "wb") as fp: fp.write(self.data) - fp.close() def zipTest(self, f, compression): # Create the ZIP archive. - zipfp = zipfile.ZipFile(f, "w", compression) - - # It will contain enough copies of self.data to reach about 6GB of - # raw data to store. - filecount = 6*1024**3 // len(self.data) - + with zipfile.ZipFile(f, "w", compression) as zipfp: next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL for num in range(filecount): zipfp.writestr("testfn%d" % num, self.data) @@ -54,10 +48,9 @@ class TestsWithSourceFile(unittest.TestC ' zipTest still writing %d of %d, be patient...' % (num, filecount)), file=sys.__stdout__) sys.__stdout__.flush() - zipfp.close() # Read the ZIP archive - zipfp = zipfile.ZipFile(f, "r", compression) + with zipfile.ZipFile(f, "r", compression) as zipfp: for num in range(filecount): self.assertEqual(zipfp.read("testfn%d" % num), self.data) # Print still working message since this test can be really slow @@ -67,7 +60,6 @@ class TestsWithSourceFile(unittest.TestC ' zipTest still reading %d of %d, be patient...' % (num, filecount)), file=sys.__stdout__) sys.__stdout__.flush() - zipfp.close() def testStored(self): # Try the temp file first. If we do TESTFN2 first, then it hogs @@ -92,7 +84,7 @@ class OtherTests(unittest.TestCase): def testMoreThan64kFiles(self): # This test checks that more than 64k files can be added to an archive, # and that the resulting archive can be read properly by ZipFile - zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=True) + with zipfile.ZipFile(TESTFN, mode="w", allowZip64=True) as zipf: zipf.debug = 100 numfiles = (1 << 16) * 3//2 for i in range(numfiles): @@ -100,12 +92,11 @@ class OtherTests(unittest.TestCase): self.assertEqual(len(zipf.namelist()), numfiles) zipf.close() - zipf2 = zipfile.ZipFile(TESTFN, mode="r") + with zipfile.ZipFile(TESTFN, mode="r") as zipf2: self.assertEqual(len(zipf2.namelist()), numfiles) for i in range(numfiles): content = zipf2.read("foo%08d" % i).decode('ascii') self.assertEqual(content, "%d" % (i**3 % 57)) - zipf2.close() def testMoreThan64kFilesAppend(self): zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=False) diff -r fc7dbba57869 Lib/test/test_zipimport.py --- a/Lib/test/test_zipimport.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_zipimport.py Fri Mar 20 09:17:09 2015 +0000 @@ -406,15 +406,12 @@ class UncompressedZipImportTestCase(Impo "need an unencodable filename") def testUnencodable(self): filename = support.TESTFN_UNENCODABLE + ".zip" - z = ZipFile(filename, "w") + with ZipFile(filename, "w") as z: + self.addCleanup(os.remove, filename) zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW)) zinfo.compress_type = self.compression z.writestr(zinfo, test_src) - z.close() - try: zipimport.zipimporter(filename) - finally: - os.remove(filename) @support.requires_zlib diff -r fc7dbba57869 Lib/test/test_zipimport_support.py --- a/Lib/test/test_zipimport_support.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/test/test_zipimport_support.py Fri Mar 20 09:17:09 2015 +0000 @@ -123,15 +123,13 @@ class ZipSupportTests(unittest.TestCase) test_src) zip_name, run_name = make_zip_script(d, 'test_zip', script_name) - z = zipfile.ZipFile(zip_name, 'a') + with zipfile.ZipFile(zip_name, 'a') as z: for mod_name, src in sample_sources.items(): z.writestr(mod_name + ".py", src) - z.close() if verbose: - zip_file = zipfile.ZipFile(zip_name, 'r') + with zipfile.ZipFile(zip_name, 'r') as zip_file: print ('Contents of %r:' % zip_name) zip_file.printdir() - zip_file.close() os.remove(script_name) sys.path.insert(0, zip_name) import test_zipped_doctest diff -r fc7dbba57869 Lib/token.py --- a/Lib/token.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/token.py Fri Mar 20 09:17:09 2015 +0000 @@ -97,8 +97,8 @@ def _main(): except OSError as err: sys.stdout.write("I/O error: %s\n" % str(err)) sys.exit(1) + with fp: lines = fp.read().split("\n") - fp.close() prog = re.compile( "#define[ \t][ \t]*([A-Z0-9][A-Z0-9_]*)[ \t][ \t]*([0-9][0-9]*)", re.IGNORECASE) @@ -116,8 +116,8 @@ def _main(): except OSError as err: sys.stderr.write("I/O error: %s\n" % str(err)) sys.exit(2) + with fp: format = fp.read().split("\n") - fp.close() try: start = format.index("#--start constants--") + 1 end = format.index("#--end constants--") @@ -133,8 +133,8 @@ def _main(): except OSError as err: sys.stderr.write("I/O error: %s\n" % str(err)) sys.exit(4) + with fp: fp.write("\n".join(format)) - fp.close() if __name__ == "__main__": diff -r fc7dbba57869 Lib/trace.py --- a/Lib/trace.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/trace.py Fri Mar 20 09:17:09 2015 +0000 @@ -232,8 +232,8 @@ class CoverageResults: if self.infile: # Try to merge existing counts file. try: - counts, calledfuncs, callers = \ - pickle.load(open(self.infile, 'rb')) + with open(self.infile, 'rb') as f: + counts, calledfuncs, callers = pickle.load(f) self.update(self.__class__(counts, calledfuncs, callers)) except (OSError, EOFError, ValueError) as err: print(("Skipping counts file %r: %s" @@ -361,6 +361,7 @@ class CoverageResults: n_lines = 0 n_hits = 0 + with outfile: for lineno, line in enumerate(lines, 1): # do the blank/comment match to try to mark more lines # (help the reader find stuff that hasn't been covered) @@ -380,7 +381,6 @@ class CoverageResults: else: outfile.write(" ") outfile.write(line.expandtabs(8)) - outfile.close() return n_hits, n_lines diff -r fc7dbba57869 Lib/xmlrpc/client.py --- a/Lib/xmlrpc/client.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Lib/xmlrpc/client.py Fri Mar 20 09:17:09 2015 +0000 @@ -1017,12 +1017,10 @@ def gzip_encode(data): """ if not gzip: raise NotImplementedError - f = BytesIO() - gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) + with BytesIO() as f: + with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf: gzf.write(data) - gzf.close() encoded = f.getvalue() - f.close() return encoded ## @@ -1041,14 +1039,12 @@ def gzip_decode(data): """ if not gzip: raise NotImplementedError - f = BytesIO(data) - gzf = gzip.GzipFile(mode="rb", fileobj=f) + with BytesIO(data) as f, \ + gzip.GzipFile(mode="rb", fileobj=f) as gzf: try: decoded = gzf.read() except OSError: raise ValueError("invalid data") - f.close() - gzf.close() return decoded ## diff -r fc7dbba57869 Parser/asdl_c.py --- a/Parser/asdl_c.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Parser/asdl_c.py Fri Mar 20 09:17:09 2015 +0000 @@ -1252,7 +1252,7 @@ def main(srcfile, dump_module=False): sys.exit(1) if INC_DIR: p = "%s/%s-ast.h" % (INC_DIR, mod.name) - f = open(p, "w") + with open(p, "w") as f: f.write(auto_gen_msg) f.write('#include "asdl.h"\n\n') c = ChainOfVisitors(TypeDefVisitor(f), @@ -1263,11 +1263,10 @@ def main(srcfile, dump_module=False): f.write("PyObject* PyAST_mod2obj(mod_ty t);\n") f.write("mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n") f.write("int PyAST_Check(PyObject* obj);\n") - f.close() if SRC_DIR: p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") - f = open(p, "w") + with open(p, "w") as f: f.write(auto_gen_msg) f.write('#include \n') f.write('\n') @@ -1286,7 +1285,6 @@ def main(srcfile, dump_module=False): PartingShots(f), ) v.visit(mod) - f.close() if __name__ == "__main__": import sys diff -r fc7dbba57869 Tools/demo/markov.py --- a/Tools/demo/markov.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/demo/markov.py Fri Mar 20 09:17:09 2015 +0000 @@ -79,8 +79,8 @@ def test(): else: f = open(filename, 'r') if debug: print('processing', filename, '...') + with f: text = f.read() - f.close() paralist = text.split('\n\n') for para in paralist: if debug > 1: print('feeding ...') diff -r fc7dbba57869 Tools/demo/rpython.py --- a/Tools/demo/rpython.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/demo/rpython.py Fri Mar 20 09:17:09 2015 +0000 @@ -22,7 +22,7 @@ def main(): port = int(port[i+1:]) host = host[:i] command = ' '.join(sys.argv[2:]) - s = socket(AF_INET, SOCK_STREAM) + with socket(AF_INET, SOCK_STREAM) as s: s.connect((host, port)) s.send(command.encode()) s.shutdown(SHUT_WR) @@ -33,6 +33,5 @@ def main(): break reply += data print(reply.decode(), end=' ') - s.close() main() diff -r fc7dbba57869 Tools/demo/rpythond.py --- a/Tools/demo/rpythond.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/demo/rpythond.py Fri Mar 20 09:17:09 2015 +0000 @@ -26,6 +26,7 @@ def main(): s.listen(1) while True: conn, (remotehost, remoteport) = s.accept() + with conn: print('connection from', remotehost, remoteport) request = b'' while 1: @@ -35,7 +36,6 @@ def main(): request += data reply = execute(request.decode()) conn.send(reply.encode()) - conn.close() def execute(request): stdout = sys.stdout diff -r fc7dbba57869 Tools/freeze/checkextensions_win32.py --- a/Tools/freeze/checkextensions_win32.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/freeze/checkextensions_win32.py Fri Mar 20 09:17:09 2015 +0000 @@ -130,7 +130,8 @@ def parse_dsp(dsp): ret = [] dsp_path, dsp_name = os.path.split(dsp) try: - lines = open(dsp, "r").readlines() + with open(dsp, "r") as fp: + lines = fp.readlines() except IOError as msg: sys.stderr.write("%s: %s\n" % (dsp, msg)) return None diff -r fc7dbba57869 Tools/freeze/freeze.py --- a/Tools/freeze/freeze.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/freeze/freeze.py Fri Mar 20 09:17:09 2015 +0000 @@ -144,7 +144,8 @@ def main(): # last option can not be "-i", so this ensures "pos+1" is in range! if sys.argv[pos] == '-i': try: - options = open(sys.argv[pos+1]).read().split() + with open(sys.argv[pos+1]) as infp: + options = infp.read().split() except IOError as why: usage("File name '%s' specified with the -i option " "can not be read - %s" % (sys.argv[pos+1], why) ) @@ -451,13 +452,12 @@ def main(): # generate config.c and Makefile builtins.sort() - infp = open(config_c_in) + with open(config_c_in) as infp: outfp = bkfile.open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() - infp.close() cflags = ['$(OPT)'] cppflags = defines + includes diff -r fc7dbba57869 Tools/i18n/msgfmt.py --- a/Tools/i18n/msgfmt.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/i18n/msgfmt.py Fri Mar 20 09:17:09 2015 +0000 @@ -109,7 +109,8 @@ def make(filename, outfile): outfile = os.path.splitext(infile)[0] + '.mo' try: - lines = open(infile, 'rb').readlines() + with open(infile, 'rb') as f: + lines = f.readlines() except IOError as msg: print(msg, file=sys.stderr) sys.exit(1) @@ -199,7 +200,8 @@ def make(filename, outfile): output = generate() try: - open(outfile,"wb").write(output) + with open(outfile,"wb") as f: + f.write(output) except IOError as msg: print(msg, file=sys.stderr) diff -r fc7dbba57869 Tools/i18n/pygettext.py --- a/Tools/i18n/pygettext.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/i18n/pygettext.py Fri Mar 20 09:17:09 2015 +0000 @@ -595,9 +595,8 @@ def main(): # initialize list of strings to exclude if options.excludefilename: try: - fp = open(options.excludefilename) + with open(options.excludefilename) as fp: options.toexclude = fp.readlines() - fp.close() except IOError: print(_( "Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr) diff -r fc7dbba57869 Tools/msi/msi.py --- a/Tools/msi/msi.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/msi/msi.py Fri Mar 20 09:17:09 2015 +0000 @@ -39,7 +39,8 @@ except ImportError: pass # Extract current version from Include/patchlevel.h -lines = open(srcdir + "/Include/patchlevel.h").readlines() +with open(srcdir + "/Include/patchlevel.h") as f: + lines = f.readlines() major = minor = micro = level = serial = None levels = { 'PY_RELEASE_LEVEL_ALPHA':0xA, @@ -149,7 +150,7 @@ def build_mingw_lib(lib_file, def_file, (dlltool, dll_file, def_file, mingw_lib) export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match - f = open(def_file,'w') + with open(def_file,'w') as f: f.write("LIBRARY %s\n" % dll_file) f.write("EXPORTS\n") @@ -158,7 +159,6 @@ def build_mingw_lib(lib_file, def_file, m = export_match(line) if m: f.write(m.group(1)+"\n") - f.close() exit = nm_pipe.close() if exit: @@ -920,9 +920,11 @@ def extract_msvcr100(): def generate_license(): import shutil, glob - out = open("LICENSE.txt", "w") - shutil.copyfileobj(open(os.path.join(srcdir, "LICENSE")), out) - shutil.copyfileobj(open("crtlicense.txt"), out) + with open("LICENSE.txt", "w") as out: + with open(os.path.join(srcdir, "LICENSE") as f: + shutil.copyfileobj(f, out) + with open("crtlicense.txt") as f: + shutil.copyfileobj(f, out) for name, pat, file in (("bzip2","bzip2-*", "LICENSE"), ("openssl", "openssl-*", "LICENSE"), ("Tcl", "tcl-8*", "license.terms"), @@ -935,8 +937,8 @@ def generate_license(): if len(dirs) > 2 and not snapshot: raise ValueError, "Multiple copies of "+pat dir = dirs[0] - shutil.copyfileobj(open(os.path.join(dir, file)), out) - out.close() + with open(os.path.join(dir, file)) as f: + shutil.copyfileobj(f, out) class PyDirectory(Directory): @@ -1358,11 +1360,10 @@ def build_pdbzip(): pdbexclude = ['kill_python.pdb', 'make_buildinfo.pdb', 'make_versioninfo.pdb'] path = "python-%s%s-pdb.zip" % (full_current_version, msilib.arch_ext) - pdbzip = zipfile.ZipFile(path, 'w') + with zipfile.ZipFile(path, 'w') as pdbzip: for f in glob.glob1(os.path.join(srcdir, PCBUILD), "*.pdb"): if f not in pdbexclude and not f.endswith('_d.pdb'): pdbzip.write(os.path.join(srcdir, PCBUILD, f), f) - pdbzip.close() db,msiname = build_database() try: diff -r fc7dbba57869 Tools/msi/msilib.py --- a/Tools/msi/msilib.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/msi/msilib.py Fri Mar 20 09:17:09 2015 +0000 @@ -649,7 +649,8 @@ class Dialog: return self.control(name, "CheckBox", x, y, w, h, attr, prop, text, next, None) def pe_type(path): - header = open(path, "rb").read(1000) + with open(path, "rb") as f: + header = f.read(1000) # offset of PE header is at offset 0x3c pe_offset = struct.unpack("%s]' % (addr2rc[addr], rc), end=' ') print(guts, addr2guts[addr]) - f.close() print("%d objects before, %d after" % (before, after)) +def combine(fname): + with open(fname) as f: + combinefile(f) + if __name__ == '__main__': combine(sys.argv[1]) diff -r fc7dbba57869 Tools/scripts/dutree.py --- a/Tools/scripts/dutree.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/dutree.py Fri Mar 20 09:17:09 2015 +0000 @@ -4,9 +4,9 @@ import os, sys, errno def main(): - p = os.popen('du ' + ' '.join(sys.argv[1:]), 'r') total, d = None, {} - for line in p.readlines(): + with os.popen('du ' + ' '.join(sys.argv[1:]), 'r') as p: + for line in p: i = 0 while line[i] in '0123456789': i = i+1 size = eval(line[:i]) diff -r fc7dbba57869 Tools/scripts/eptags.py --- a/Tools/scripts/eptags.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/eptags.py Fri Mar 20 09:17:09 2015 +0000 @@ -28,6 +28,7 @@ def treat_file(filename, outfp): except: sys.stderr.write('Cannot open %s\n'%filename) return + with fp: charno = 0 lineno = 0 tags = [] @@ -48,7 +49,7 @@ def treat_file(filename, outfp): outfp.write(tag) def main(): - outfp = open('TAGS', 'w') + with open('TAGS', 'w') as outfp: for filename in sys.argv[1:]: treat_file(filename, outfp) diff -r fc7dbba57869 Tools/scripts/finddiv.py --- a/Tools/scripts/finddiv.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/finddiv.py Fri Mar 20 09:17:09 2015 +0000 @@ -55,6 +55,7 @@ def process(filename, listnames): except IOError as msg: sys.stderr.write("Can't open: %s\n" % msg) return 1 + with fp: g = tokenize.generate_tokens(fp.readline) lastrow = None for type, token, (row, col), end, line in g: @@ -65,7 +66,6 @@ def process(filename, listnames): if row != lastrow: lastrow = row print("%s:%d:%s" % (filename, row, line), end=' ') - fp.close() def processdir(dir, listnames): try: diff -r fc7dbba57869 Tools/scripts/fixcid.py --- a/Tools/scripts/fixcid.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/fixcid.py Fri Mar 20 09:17:09 2015 +0000 @@ -279,6 +279,7 @@ def addsubst(substfile): except IOError as msg: err(substfile + ': cannot read substfile: ' + str(msg) + '\n') sys.exit(1) + with fp: lineno = 0 while 1: line = fp.readline() @@ -308,7 +309,6 @@ def addsubst(substfile): err('%s:%r: warning: overriding: %r %r\n' % (substfile, lineno, key, value)) err('%s:%r: warning: previous: %r\n' % (substfile, lineno, Dict[key])) Dict[key] = value - fp.close() if __name__ == '__main__': main() diff -r fc7dbba57869 Tools/scripts/fixdiv.py --- a/Tools/scripts/fixdiv.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/fixdiv.py Fri Mar 20 09:17:09 2015 +0000 @@ -185,6 +185,7 @@ def readwarnings(warningsfile): sys.stderr.write("can't open: %s\n" % msg) return warnings = {} + with f: while 1: line = f.readline() if not line: @@ -199,7 +200,6 @@ def readwarnings(warningsfile): if list is None: warnings[filename] = list = [] list.append((int(lineno), sys.intern(what))) - f.close() return warnings def process(filename, list): @@ -210,6 +210,7 @@ def process(filename, list): except IOError as msg: sys.stderr.write("can't open: %s\n" % msg) return 1 + with fp: print("Index:", filename) f = FileContext(fp) list.sort() @@ -284,10 +285,9 @@ def process(filename, list): print("True division / operator at line %d:" % row) print("=", line) elif intlong and floatcomplex: - print("*** Ambiguous / operator (%s, %s) at line %d:" % ( - "|".join(intlong), "|".join(floatcomplex), row)) + print("*** Ambiguous / operator (%s, %s) at line %d:" % + ("|".join(intlong), "|".join(floatcomplex), row)) print("?", line) - fp.close() def reportphantomwarnings(warnings, f): blocks = [] diff -r fc7dbba57869 Tools/scripts/fixheader.py --- a/Tools/scripts/fixheader.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/fixheader.py Fri Mar 20 09:17:09 2015 +0000 @@ -15,8 +15,8 @@ def process(filename): except IOError as msg: sys.stderr.write('%s: can\'t open: %s\n' % (filename, str(msg))) return + with f: data = f.read() - f.close() if data[:2] != '/*': sys.stderr.write('%s does not begin with C comment\n' % filename) return @@ -31,19 +31,19 @@ def process(filename): if ord(c)<=0x80 and c.isalnum(): magic = magic + c.upper() else: magic = magic + '_' - sys.stdout = f - print('#ifndef', magic) - print('#define', magic) - print('#ifdef __cplusplus') - print('extern "C" {') - print('#endif') - print() + with f: + print('#ifndef', magic, file=f) + print('#define', magic, file=f) + print('#ifdef __cplusplus', file=f) + print('extern "C" {', file=f) + print('#endif', file=f) + print(file=f) f.write(data) - print() - print('#ifdef __cplusplus') - print('}') - print('#endif') - print('#endif /*', '!'+magic, '*/') + print(file=f) + print('#ifdef __cplusplus', file=f) + print('}', file=f) + print('#endif', file=f) + print('#endif /*', '!'+magic, '*/', file=f) if __name__ == '__main__': main() diff -r fc7dbba57869 Tools/scripts/fixnotice.py --- a/Tools/scripts/fixnotice.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/fixnotice.py Fri Mar 20 09:17:09 2015 +0000 @@ -73,22 +73,19 @@ def main(): elif opt == '--dry-run': DRYRUN = 1 elif opt == '--oldnotice': - fp = open(arg) + with open(arg) as fp: OLD_NOTICE = fp.read() - fp.close() elif opt == '--newnotice': - fp = open(arg) + with open(arg) as fp: NEW_NOTICE = fp.read() - fp.close() for arg in args: process(arg) def process(file): - f = open(file) + with open(file) as f: data = f.read() - f.close() i = data.find(OLD_NOTICE) if i < 0: if VERBOSE: @@ -102,9 +99,8 @@ def process(file): data = data[:i] + NEW_NOTICE + data[i+len(OLD_NOTICE):] new = file + ".new" backup = file + ".bak" - f = open(new, "w") + with open(new, "w") as f: f.write(data) - f.close() os.rename(file, backup) os.rename(new, file) diff -r fc7dbba57869 Tools/scripts/fixps.py --- a/Tools/scripts/fixps.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/fixps.py Fri Mar 20 09:17:09 2015 +0000 @@ -14,20 +14,18 @@ def main(): except IOError as msg: print(filename, ': can\'t open :', msg) continue + with f: line = f.readline() if not re.match('^#! */usr/local/bin/python', line): print(filename, ': not a /usr/local/bin/python script') - f.close() continue rest = f.read() - f.close() line = re.sub('/usr/local/bin/python', '/usr/bin/env python', line) print(filename, ':', repr(line)) - f = open(filename, "w") + with open(filename, "w") as f: f.write(line) f.write(rest) - f.close() if __name__ == '__main__': main() diff -r fc7dbba57869 Tools/scripts/ftpmirror.py --- a/Tools/scripts/ftpmirror.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/ftpmirror.py Fri Mar 20 09:17:09 2015 +0000 @@ -113,7 +113,8 @@ def mirrorsubdir(f, localdir): return infofilename = os.path.join(localdir, '.mirrorinfo') try: - text = open(infofilename, 'r').read() + with open(infofilename, 'r') as fd: + text = fd.read() except IOError as msg: text = '{}' try: @@ -388,12 +389,11 @@ def writedict(dict, filename): os.unlink(backup) except OSError: pass - fp = open(tempname, 'w') + with open(tempname, 'w') as fp: fp.write('{\n') for key, value in dict.items(): fp.write('%r: %r,\n' % (key, value)) fp.write('}\n') - fp.close() try: os.rename(filename, backup) except OSError: diff -r fc7dbba57869 Tools/scripts/get-remote-certificate.py --- a/Tools/scripts/get-remote-certificate.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/get-remote-certificate.py Fri Mar 20 09:17:09 2015 +0000 @@ -29,9 +29,8 @@ def fetch_server_certificate (host, port return None else: tn = tempfile.mktemp() - fp = open(tn, "wb") + with open(tn, "wb") as fp: fp.write(m.group(1) + b"\n") - fp.close() try: tn2 = (outfile or tempfile.mktemp()) status, output = subproc(r'openssl x509 -in "%s" -out "%s"' % @@ -39,9 +38,8 @@ def fetch_server_certificate (host, port if status != 0: raise RuntimeError('OpenSSL x509 failed with status %s and ' 'output: %r' % (status, output)) - fp = open(tn2, 'rb') + with open(tn2, 'rb') as fp: data = fp.read() - fp.close() os.unlink(tn2) return data finally: @@ -49,9 +47,8 @@ def fetch_server_certificate (host, port if sys.platform.startswith("win"): tfile = tempfile.mktemp() - fp = open(tfile, "w") + with open(tfile, "w") as fp: fp.write("quit\n") - fp.close() try: status, output = subproc( 'openssl s_client -connect "%s:%s" -showcerts < "%s"' % diff -r fc7dbba57869 Tools/scripts/gprof2html.py --- a/Tools/scripts/gprof2html.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/gprof2html.py Fri Mar 20 09:17:09 2015 +0000 @@ -24,14 +24,7 @@ def add_escapes(filename): for line in fp: yield cgi.escape(line) - -def main(): - filename = "gprof.out" - if sys.argv[1:]: - filename = sys.argv[1] - outputfilename = filename + ".html" - input = add_escapes(filename) - output = open(outputfilename, "w") +def gprof2html(input, output, filename): output.write(header % filename) for line in input: output.write(line) @@ -74,7 +67,16 @@ def main(): part = '%s' % (part, part) output.write(part) output.write(trailer) - output.close() + + +def main(): + filename = "gprof.out" + if sys.argv[1:]: + filename = sys.argv[1] + outputfilename = filename + ".html" + input = add_escapes(filename) + with open(outputfilename, "w") as output: + gprof2html(input, output, filename) webbrowser.open("file:" + os.path.abspath(outputfilename)) if __name__ == '__main__': diff -r fc7dbba57869 Tools/scripts/h2py.py --- a/Tools/scripts/h2py.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/h2py.py Fri Mar 20 09:17:09 2015 +0000 @@ -69,13 +69,13 @@ def main(): sys.stdout.write('# Generated by h2py from stdin\n') process(sys.stdin, sys.stdout) else: - fp = open(filename, 'r') + with open(filename, 'r') as fp: outfile = os.path.basename(filename) i = outfile.rfind('.') if i > 0: outfile = outfile[:i] modname = outfile.upper() outfile = modname + '.py' - outfp = open(outfile, 'w') + with open(outfile, 'w') as outfp: outfp.write('# Generated by h2py from %s\n' % filename) filedict = {} for dir in searchdirs: @@ -84,8 +84,6 @@ def main(): importable[filename[len(dir)+1:]] = modname break process(fp, outfp) - outfp.close() - fp.close() def pytify(body): # replace ignored patterns by spaces @@ -161,6 +159,7 @@ def process(fp, outfp, env = {}): except IOError: pass if inclfp: + with inclfp: outfp.write( '\n# Included from %s\n' % filename) process(inclfp, outfp, env) diff -r fc7dbba57869 Tools/scripts/ifdef.py --- a/Tools/scripts/ifdef.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/ifdef.py Fri Mar 20 09:17:09 2015 +0000 @@ -45,9 +45,8 @@ def main(): if filename == '-': process(sys.stdin, sys.stdout) else: - f = open(filename, 'r') + with open(filename, 'r') as f: process(f, sys.stdout) - f.close() def process(fpi, fpo): keywords = ('if', 'ifdef', 'ifndef', 'else', 'endif') diff -r fc7dbba57869 Tools/scripts/md5sum.py --- a/Tools/scripts/md5sum.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/md5sum.py Fri Mar 20 09:17:09 2015 +0000 @@ -47,10 +47,10 @@ def printsum(filename, out=sys.stdout): except IOError as msg: sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg)) return 1 + with fp: if fnfilter: filename = fnfilter(filename) sts = printsumfp(fp, filename, out) - fp.close() return sts def printsumfp(fp, filename, out=sys.stdout): diff -r fc7dbba57869 Tools/scripts/mkreal.py --- a/Tools/scripts/mkreal.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/mkreal.py Fri Mar 20 09:17:09 2015 +0000 @@ -18,14 +18,13 @@ def mkrealfile(name): st = os.stat(name) # Get the mode mode = S_IMODE(st[ST_MODE]) linkto = os.readlink(name) # Make sure again it's a symlink - f_in = open(name, 'r') # This ensures it's a file + with open(name, 'rb') as f_in: # This ensures it's a file os.unlink(name) - f_out = open(name, 'w') + with open(name, 'wb') as f_out: while 1: buf = f_in.read(BUFSIZE) if not buf: break f_out.write(buf) - del f_out # Flush data to disk before changing mode os.chmod(name, mode) def mkrealdir(name): diff -r fc7dbba57869 Tools/scripts/nm2def.py --- a/Tools/scripts/nm2def.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/nm2def.py Fri Mar 20 09:17:09 2015 +0000 @@ -42,7 +42,8 @@ NM = 'nm -p -g %s' def symbols(lib=PYTHONLIB,types=('T','C','D')): - lines = os.popen(NM % lib).readlines() + with os.popen(NM % lib) as pipe: + lines = pipe.readlines() lines = [s.strip() for s in lines] symbols = {} for line in lines: @@ -97,7 +98,7 @@ def main(): exports = export_list(s) f = sys.stdout # open('PC/python_nt.def','w') f.write(DEF_TEMPLATE % (exports)) - f.close() + # f.close() if __name__ == '__main__': main() diff -r fc7dbba57869 Tools/scripts/objgraph.py --- a/Tools/scripts/objgraph.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/objgraph.py Fri Mar 20 09:17:09 2015 +0000 @@ -180,7 +180,8 @@ def main(): if filename == '-': readinput(sys.stdin) else: - readinput(open(filename, 'r')) + with open(filename, 'r') as f: + readinput(f) # warndups() # diff -r fc7dbba57869 Tools/scripts/parseentities.py --- a/Tools/scripts/parseentities.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/parseentities.py Fri Mar 20 09:17:09 2015 +0000 @@ -50,13 +50,15 @@ def writefile(f,defs): if __name__ == '__main__': if len(sys.argv) > 1: - infile = open(sys.argv[1]) + with open(sys.argv[1]) as infile: + text = infile.read() else: - infile = sys.stdin + text = sys.stdin.read() + + defs = parse(text) + if len(sys.argv) > 2: - outfile = open(sys.argv[2],'w') + with open(sys.argv[2],'w') as outfile: + writefile(outfile, defs) else: - outfile = sys.stdout - text = infile.read() - defs = parse(text) - writefile(outfile,defs) + writefile(sys.stdout, defs) diff -r fc7dbba57869 Tools/scripts/pathfix.py --- a/Tools/scripts/pathfix.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/pathfix.py Fri Mar 20 09:17:09 2015 +0000 @@ -97,20 +97,20 @@ def fix(filename): except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 + with f: line = f.readline() fixed = fixline(line) if line == fixed: rep(filename+': no change\n') - f.close() return head, tail = os.path.split(filename) tempname = os.path.join(head, '@' + tail) try: g = open(tempname, 'wb') except IOError as msg: - f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 + with g: rep(filename + ': updating\n') g.write(fixed) BUFSIZE = 8*1024 @@ -118,8 +118,6 @@ def fix(filename): buf = f.read(BUFSIZE) if not buf: break g.write(buf) - g.close() - f.close() # Finishing touch -- move files diff -r fc7dbba57869 Tools/scripts/pdeps.py --- a/Tools/scripts/pdeps.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/pdeps.py Fri Mar 20 09:17:09 2015 +0000 @@ -64,7 +64,7 @@ m_from = re.compile('^[ \t]*import[ \t]+ # Collect data from one file # def process(filename, table): - fp = open(filename, 'r') + with open(filename, 'r') as fp: mod = os.path.basename(filename) if mod[-3:] == '.py': mod = mod[:-3] @@ -86,7 +86,6 @@ def process(filename, table): word = word.strip() if word not in list: list.append(word) - fp.close() # Compute closure (this is in fact totally general) diff -r fc7dbba57869 Tools/scripts/ptags.py --- a/Tools/scripts/ptags.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/ptags.py Fri Mar 20 09:17:09 2015 +0000 @@ -19,7 +19,7 @@ def main(): for filename in args: treat_file(filename) if tags: - fp = open('tags', 'w') + with open('tags', 'w') as fp: tags.sort() for s in tags: fp.write(s) @@ -33,6 +33,7 @@ def treat_file(filename): except: sys.stderr.write('Cannot open %s\n' % filename) return + with fp: base = os.path.basename(filename) if base[-3:] == '.py': base = base[:-3] diff -r fc7dbba57869 Tools/scripts/rgrep.py --- a/Tools/scripts/rgrep.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/rgrep.py Fri Mar 20 09:17:09 2015 +0000 @@ -30,6 +30,7 @@ def main(): f = open(filename) except IOError as msg: usage("can't open %r: %s" % (filename, msg), 1) + with f: f.seek(0, 2) pos = f.tell() leftover = None diff -r fc7dbba57869 Tools/scripts/svneol.py --- a/Tools/scripts/svneol.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/svneol.py Fri Mar 20 09:17:09 2015 +0000 @@ -39,7 +39,8 @@ import subprocess def propfiles(root, fn): default = os.path.join(root, ".svn", "props", fn + ".svn-work") try: - format = int(open(os.path.join(root, ".svn", "format")).read().strip()) + with open(os.path.join(root, ".svn", "format")) as f: + format = int(f.read().strip()) except IOError: return [] if format in (8, 9): @@ -60,6 +61,7 @@ def proplist(root, fn): # no properties file: not under version control, # or no properties set continue + with f: while True: # key-value pairs, of the form # K @@ -80,7 +82,6 @@ def proplist(root, fn): L = int(line.split()[1]) value = f.read(L) f.readline() - f.close() return result diff -r fc7dbba57869 Tools/scripts/texi2html.py --- a/Tools/scripts/texi2html.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/texi2html.py Fri Mar 20 09:17:09 2015 +0000 @@ -118,11 +118,10 @@ class HTMLNode: self.lines.append(line) def flush(self): - fp = open(self.dirname + '/' + makefile(self.name), 'w') + with open(self.dirname + '/' + makefile(self.name), 'w') as fp: fp.write(self.prologue) fp.write(self.text) fp.write(self.epilogue) - fp.close() def link(self, label, nodename, rel=None, rev=None): if nodename: @@ -558,6 +557,7 @@ class TexinfoParser: except IOError as msg: print('*** Can\'t open include file', repr(file)) return + with fp: print('!'*self.debugging, '--> file', repr(file)) save_done = self.done save_skip = self.skip @@ -565,7 +565,6 @@ class TexinfoParser: self.includedepth = self.includedepth + 1 self.parserest(fp, 0) self.includedepth = self.includedepth - 1 - fp.close() self.done = save_done self.skip = save_skip self.stack = save_stack @@ -1770,7 +1769,7 @@ class HTMLHelp: # PROJECT FILE try: - fp = open(projectfile,'w') + with open(projectfile, 'w') as fp: print('[OPTIONS]', file=fp) print('Auto Index=Yes', file=fp) print('Binary TOC=No', file=fp) @@ -1794,14 +1793,13 @@ class HTMLHelp: print('[FILES]', file=fp) print('', file=fp) self.dumpfiles(fp) - fp.close() except IOError as msg: print(projectfile, ':', msg) sys.exit(1) # CONTENT FILE try: - fp = open(contentfile,'w') + with open(contentfile, 'w') as fp: print('', file=fp) print('', file=fp) print('', file=fp) @@ -1819,14 +1817,13 @@ class HTMLHelp: self.dumpnodes(fp) print('', file=fp) print('', file=fp) - fp.close() except IOError as msg: print(contentfile, ':', msg) sys.exit(1) # INDEX FILE try: - fp = open(indexfile ,'w') + with open(indexfile, 'w') as fp: print('', file=fp) print('', file=fp) print('', file=fp) @@ -1841,7 +1838,6 @@ class HTMLHelp: self.dumpindex(fp) print('', file=fp) print('', file=fp) - fp.close() except IOError as msg: print(indexfile , ':', msg) sys.exit(1) @@ -2064,8 +2060,8 @@ def test(): print(file, ':', msg) sys.exit(1) + with fp: parser.parse(fp) - fp.close() parser.report() htmlhelp.finalize() diff -r fc7dbba57869 Tools/scripts/treesync.py --- a/Tools/scripts/treesync.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/scripts/treesync.py Fri Mar 20 09:17:09 2015 +0000 @@ -23,7 +23,7 @@ entry in the master tree are synchronize """ -import os, sys, stat, getopt +import os, sys, stat, getopt, shutil # Interactivity options default_answer = "ask" @@ -96,7 +96,9 @@ def process(slave, master): subdirs.append((slavename, mastername)) if cvsdir: entries = os.path.join(cvsdir, "Entries") - for e in open(entries).readlines(): + with open(entries) as f: + lines = f.readlines() + for e in lines: words = e.split('/') if words[0] == '' and words[1:]: name = words[1] @@ -110,47 +112,45 @@ def compare(slave, master): try: sf = open(slave, 'r') except IOError: - sf = None try: - mf = open(master, 'rb') + with open(master, 'rb'): pass except IOError: - mf = None - if not sf: - if not mf: print("Neither master nor slave exists", master) return print("Creating missing slave", slave) copy(master, slave, answer=create_files) return - if not mf: + with sf: + try: + mf = open(master, 'rb') + except IOError: print("Not updating missing master", master) return - if sf and mf: + with mf: if identical(sf, mf): return sft = mtime(sf) mft = mtime(mf) if mft > sft: # Master is newer -- copy master to slave - sf.close() - mf.close() print("Master ", master) print("is newer than slave", slave) - copy(master, slave, answer=write_slave) - return + args = (master, slave) + answer = write_slave + else: # Slave is newer -- copy slave to master print("Slave is", sft-mft, "seconds newer than master") # But first check what to do about CRLF mf.seek(0) fun = funnychars(mf) - mf.close() - sf.close() if fun: print("***UPDATING MASTER (BINARY COPY)***") - copy(slave, master, "rb", answer=write_master) + args = (slave, master, "rb") else: print("***UPDATING MASTER***") - copy(slave, master, "r", answer=write_master) + args = (slave, master, "r") + answer=write_master + copy(*args, answer=answer) BUFSIZE = 16*1024 @@ -178,14 +178,12 @@ def copy(src, dst, rmode="rb", wmode="wb print(" to", dst) if not okay("okay to copy? ", answer): return - f = open(src, rmode) - g = open(dst, wmode) + with open(src, rmode) as f, \ + open(dst, wmode) as g: while 1: buf = f.read(BUFSIZE) if not buf: break g.write(buf) - f.close() - g.close() def raw_input(prompt): sys.stdout.write(prompt) diff -r fc7dbba57869 Tools/unicode/gencjkcodecs.py --- a/Tools/unicode/gencjkcodecs.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/unicode/gencjkcodecs.py Fri Mar 20 09:17:09 2015 +0000 @@ -61,7 +61,8 @@ def gencodecs(prefix): encoding=enc.lower(), owner=loc) codecpath = os.path.join(prefix, enc + '.py') - open(codecpath, 'w').write(code) + with open(codecpath, 'w') as f: + f.write(code) if __name__ == '__main__': import sys diff -r fc7dbba57869 Tools/unicode/gencodec.py --- a/Tools/unicode/gencodec.py Sun Nov 09 20:48:36 2014 +0200 +++ b/Tools/unicode/gencodec.py Fri Mar 20 09:17:09 2015 +0000 @@ -72,9 +72,8 @@ def parsecodes(codes, len=len, range=ran def readmap(filename): - f = open(filename,'r') + with open(filename,'r') as f: lines = f.readlines() - f.close() enc2uni = {} identity = [] unmapped = list(range(256)) @@ -359,18 +358,16 @@ encoding_table = codecs.charmap_build(de def pymap(name,map,pyfile,encodingname,comments=1): code = codegen(name,map,encodingname,comments) - f = open(pyfile,'w') + with open(pyfile,'w') as f: f.write(code) - f.close() def marshalmap(name,map,marshalfile): d = {} for e,(u,c) in map.items(): d[e] = (u,c) - f = open(marshalfile,'wb') + with open(marshalfile,'wb') as f: marshal.dump(d,f) - f.close() def convertdir(dir, dirprefix='', nameprefix='', comments=1): @@ -411,8 +408,8 @@ def rewritepythondir(dir, dirprefix='', print('converting %s to %s' % (mapname, dirprefix + codefile)) try: - map = marshal.load(open(os.path.join(dir,mapname), - 'rb')) + with open(os.path.join(dir, mapname), 'rb') as f: + map = marshal.load(f) if not map: print('* map is empty; skipping') else: