modernize some modules' code by using with statement around open()

This commit is contained in:
Giampaolo Rodola' 2013-02-12 02:04:27 +01:00
parent fd6e6cfa29
commit 2f50aaf2ff
14 changed files with 50 additions and 89 deletions

View File

@ -2010,16 +2010,13 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
# replace arguments referencing files with the file content # replace arguments referencing files with the file content
else: else:
try: try:
args_file = open(arg_string[1:]) with open(arg_string[1:]) as args_file:
try:
arg_strings = [] arg_strings = []
for arg_line in args_file.read().splitlines(): for arg_line in args_file.read().splitlines():
for arg in self.convert_arg_line_to_args(arg_line): for arg in self.convert_arg_line_to_args(arg_line):
arg_strings.append(arg) arg_strings.append(arg)
arg_strings = self._read_args_from_files(arg_strings) arg_strings = self._read_args_from_files(arg_strings)
new_arg_strings.extend(arg_strings) new_arg_strings.extend(arg_strings)
finally:
args_file.close()
except OSError: except OSError:
err = _sys.exc_info()[1] err = _sys.exc_info()[1]
self.error(str(err)) self.error(str(err))

View File

@ -77,10 +77,9 @@ class Profile(_lsprof.Profiler):
def dump_stats(self, file): def dump_stats(self, file):
import marshal import marshal
f = open(file, 'wb') with open(file, 'wb') as f:
self.create_stats() self.create_stats()
marshal.dump(self.stats, f) marshal.dump(self.stats, f)
f.close()
def create_stats(self): def create_stats(self):
self.disable() self.disable()

View File

@ -1761,11 +1761,8 @@ class FileCookieJar(CookieJar):
if self.filename is not None: filename = self.filename if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT) else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename) with open(filename) as f:
try:
self._really_load(f, filename, ignore_discard, ignore_expires) self._really_load(f, filename, ignore_discard, ignore_expires)
finally:
f.close()
def revert(self, filename=None, def revert(self, filename=None,
ignore_discard=False, ignore_expires=False): ignore_discard=False, ignore_expires=False):
@ -1856,15 +1853,12 @@ class LWPCookieJar(FileCookieJar):
if self.filename is not None: filename = self.filename if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT) else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename, "w") with open(filename, "w") as f:
try:
# There really isn't an LWP Cookies 2.0 format, but this indicates # There really isn't an LWP Cookies 2.0 format, but this indicates
# that there is extra information in here (domain_dot and # that there is extra information in here (domain_dot and
# port_spec) while still being compatible with libwww-perl, I hope. # port_spec) while still being compatible with libwww-perl, I hope.
f.write("#LWP-Cookies-2.0\n") f.write("#LWP-Cookies-2.0\n")
f.write(self.as_lwp_str(ignore_discard, ignore_expires)) f.write(self.as_lwp_str(ignore_discard, ignore_expires))
finally:
f.close()
def _really_load(self, f, filename, ignore_discard, ignore_expires): def _really_load(self, f, filename, ignore_discard, ignore_expires):
magic = f.readline() magic = f.readline()
@ -2055,8 +2049,7 @@ class MozillaCookieJar(FileCookieJar):
if self.filename is not None: filename = self.filename if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT) else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename, "w") with open(filename, "w") as f:
try:
f.write(self.header) f.write(self.header)
now = time.time() now = time.time()
for cookie in self: for cookie in self:
@ -2085,5 +2078,3 @@ class MozillaCookieJar(FileCookieJar):
"\t".join([cookie.domain, initial_dot, cookie.path, "\t".join([cookie.domain, initial_dot, cookie.path,
secure, expires, name, value])+ secure, expires, name, value])+
"\n") "\n")
finally:
f.close()

View File

@ -85,9 +85,8 @@ def main():
sys.exit(1) sys.exit(1)
# write the output file # write the output file
fp = open(optfile, 'w') with open(optfile, 'w') as fp:
fp.write(''.join(format)) fp.write(''.join(format))
fp.close()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -86,15 +86,13 @@ class Grammar(object):
def dump(self, filename): def dump(self, filename):
"""Dump the grammar tables to a pickle file.""" """Dump the grammar tables to a pickle file."""
f = open(filename, "wb") with open(filename, "wb") as f:
pickle.dump(self.__dict__, f, 2) pickle.dump(self.__dict__, f, 2)
f.close()
def load(self, filename): def load(self, filename):
"""Load the grammar tables from a pickle file.""" """Load the grammar tables from a pickle file."""
f = open(filename, "rb") with open(filename, "rb") as f:
d = pickle.load(f) d = pickle.load(f)
f.close()
self.__dict__.update(d) self.__dict__.update(d)
def copy(self): def copy(self):

View File

@ -366,14 +366,11 @@ class Maildir(Mailbox):
def get_message(self, key): def get_message(self, key):
"""Return a Message representation or raise a KeyError.""" """Return a Message representation or raise a KeyError."""
subpath = self._lookup(key) subpath = self._lookup(key)
f = open(os.path.join(self._path, subpath), 'rb') with open(os.path.join(self._path, subpath), 'rb') as f:
try:
if self._factory: if self._factory:
msg = self._factory(f) msg = self._factory(f)
else: else:
msg = MaildirMessage(f) msg = MaildirMessage(f)
finally:
f.close()
subdir, name = os.path.split(subpath) subdir, name = os.path.split(subpath)
msg.set_subdir(subdir) msg.set_subdir(subdir)
if self.colon in name: if self.colon in name:
@ -383,11 +380,8 @@ class Maildir(Mailbox):
def get_bytes(self, key): def get_bytes(self, key):
"""Return a bytes representation or raise a KeyError.""" """Return a bytes representation or raise a KeyError."""
f = open(os.path.join(self._path, self._lookup(key)), 'rb') with open(os.path.join(self._path, self._lookup(key)), 'rb') as f:
try:
return f.read().replace(linesep, b'\n') return f.read().replace(linesep, b'\n')
finally:
f.close()
def get_file(self, key): def get_file(self, key):
"""Return a file-like representation or raise a KeyError.""" """Return a file-like representation or raise a KeyError."""
@ -1033,7 +1027,7 @@ class MH(Mailbox):
raise KeyError('No message with key: %s' % key) raise KeyError('No message with key: %s' % key)
else: else:
raise raise
try: with f:
if self._locked: if self._locked:
_lock_file(f) _lock_file(f)
try: try:
@ -1041,8 +1035,6 @@ class MH(Mailbox):
finally: finally:
if self._locked: if self._locked:
_unlock_file(f) _unlock_file(f)
finally:
f.close()
for name, key_list in self.get_sequences().items(): for name, key_list in self.get_sequences().items():
if key in key_list: if key in key_list:
msg.add_sequence(name) msg.add_sequence(name)
@ -1060,7 +1052,7 @@ class MH(Mailbox):
raise KeyError('No message with key: %s' % key) raise KeyError('No message with key: %s' % key)
else: else:
raise raise
try: with f:
if self._locked: if self._locked:
_lock_file(f) _lock_file(f)
try: try:
@ -1068,8 +1060,6 @@ class MH(Mailbox):
finally: finally:
if self._locked: if self._locked:
_unlock_file(f) _unlock_file(f)
finally:
f.close()
def get_file(self, key): def get_file(self, key):
"""Return a file-like representation or raise a KeyError.""" """Return a file-like representation or raise a KeyError."""

View File

@ -349,9 +349,8 @@ class ImpLoader:
self.file.close() self.file.close()
elif mod_type==imp.PY_COMPILED: elif mod_type==imp.PY_COMPILED:
if os.path.exists(self.filename[:-1]): if os.path.exists(self.filename[:-1]):
f = open(self.filename[:-1], 'r') with open(self.filename[:-1], 'r') as f:
self.source = f.read() self.source = f.read()
f.close()
elif mod_type==imp.PKG_DIRECTORY: elif mod_type==imp.PKG_DIRECTORY:
self.source = self._get_delegate().get_source() self.source = self._get_delegate().get_source()
return self.source return self.source
@ -591,12 +590,12 @@ def extend_path(path, name):
sys.stderr.write("Can't open %s: %s\n" % sys.stderr.write("Can't open %s: %s\n" %
(pkgfile, msg)) (pkgfile, msg))
else: else:
for line in f: with f:
line = line.rstrip('\n') for line in f:
if not line or line.startswith('#'): line = line.rstrip('\n')
continue if not line or line.startswith('#'):
path.append(line) # Don't check for existence! continue
f.close() path.append(line) # Don't check for existence!
return path return path

View File

@ -373,10 +373,9 @@ class Profile:
print_stats() print_stats()
def dump_stats(self, file): def dump_stats(self, file):
f = open(file, 'wb') with open(file, 'wb') as f:
self.create_stats() self.create_stats()
marshal.dump(self.stats, f) marshal.dump(self.stats, f)
f.close()
def create_stats(self): def create_stats(self):
self.simulate_cmd_complete() self.simulate_cmd_complete()

View File

@ -93,9 +93,8 @@ class Stats:
self.stats = {} self.stats = {}
return return
elif isinstance(arg, str): elif isinstance(arg, str):
f = open(arg, 'rb') with open(arg, 'rb') as f:
self.stats = marshal.load(f) self.stats = marshal.load(f)
f.close()
try: try:
file_stats = os.stat(arg) file_stats = os.stat(arg)
arg = time.ctime(file_stats.st_mtime) + " " + arg arg = time.ctime(file_stats.st_mtime) + " " + arg
@ -149,11 +148,8 @@ class Stats:
def dump_stats(self, filename): def dump_stats(self, filename):
"""Write the profile data to a file we know how to load back.""" """Write the profile data to a file we know how to load back."""
f = open(filename, 'wb') with open(filename, 'wb') as f:
try:
marshal.dump(self.stats, f) marshal.dump(self.stats, f)
finally:
f.close()
# list the tuple indices and directions for sorting, # list the tuple indices and directions for sorting,
# along with some printable description # along with some printable description

View File

@ -1426,9 +1426,8 @@ def tempfilepager(text, cmd):
"""Page through text by invoking a program on a temporary file.""" """Page through text by invoking a program on a temporary file."""
import tempfile import tempfile
filename = tempfile.mktemp() filename = tempfile.mktemp()
file = open(filename, 'w') with open(filename, 'w') as file:
file.write(text) file.write(text)
file.close()
try: try:
os.system(cmd + ' "' + filename + '"') os.system(cmd + ' "' + filename + '"')
finally: finally:

View File

@ -384,9 +384,8 @@ class _Printer(object):
for filename in self.__files: for filename in self.__files:
filename = os.path.join(dir, filename) filename = os.path.join(dir, filename)
try: try:
fp = open(filename, "r") with open(filename, "r") as fp:
data = fp.read() data = fp.read()
fp.close()
break break
except OSError: except OSError:
pass pass

View File

@ -235,7 +235,8 @@ class Symbol(object):
if __name__ == "__main__": if __name__ == "__main__":
import os, sys import os, sys
src = open(sys.argv[0]).read() with open(sys.argv[0]) as f:
src = f.read()
mod = symtable(src, os.path.split(sys.argv[0])[1], "exec") mod = symtable(src, os.path.split(sys.argv[0])[1], "exec")
for ident in mod.get_identifiers(): for ident in mod.get_identifiers():
info = mod.lookup(ident) info = mod.lookup(ident)

View File

@ -3843,18 +3843,18 @@ def write_docstringdict(filename="turtle_docstringdict"):
key = "Turtle."+methodname key = "Turtle."+methodname
docsdict[key] = eval(key).__doc__ docsdict[key] = eval(key).__doc__
f = open("%s.py" % filename,"w") with open("%s.py" % filename,"w") as f:
keys = sorted([x for x in docsdict.keys() keys = sorted([x for x in docsdict.keys()
if x.split('.')[1] not in _alias_list]) if x.split('.')[1] not in _alias_list])
f.write('docsdict = {\n\n') f.write('docsdict = {\n\n')
for key in keys[:-1]: for key in keys[:-1]:
f.write('%s :\n' % repr(key))
f.write(' """%s\n""",\n\n' % docsdict[key])
key = keys[-1]
f.write('%s :\n' % repr(key)) f.write('%s :\n' % repr(key))
f.write(' """%s\n""",\n\n' % docsdict[key]) f.write(' """%s\n"""\n\n' % docsdict[key])
key = keys[-1] f.write("}\n")
f.write('%s :\n' % repr(key)) f.close()
f.write(' """%s\n"""\n\n' % docsdict[key])
f.write("}\n")
f.close()
def read_docstrings(lang): def read_docstrings(lang):
"""Read in docstrings from lang-specific docstring dictionary. """Read in docstrings from lang-specific docstring dictionary.

View File

@ -905,11 +905,8 @@ def parse(file, namespaces=True):
builder = ExpatBuilder() builder = ExpatBuilder()
if isinstance(file, str): if isinstance(file, str):
fp = open(file, 'rb') with open(file, 'rb') as fp:
try:
result = builder.parseFile(fp) result = builder.parseFile(fp)
finally:
fp.close()
else: else:
result = builder.parseFile(file) result = builder.parseFile(file)
return result return result
@ -939,11 +936,8 @@ def parseFragment(file, context, namespaces=True):
builder = FragmentBuilder(context) builder = FragmentBuilder(context)
if isinstance(file, str): if isinstance(file, str):
fp = open(file, 'rb') with open(file, 'rb') as fp:
try:
result = builder.parseFile(fp) result = builder.parseFile(fp)
finally:
fp.close()
else: else:
result = builder.parseFile(file) result = builder.parseFile(file)
return result return result