Permalink
Browse files

Made more extensive usage of context managers with open.

  • Loading branch information...
1 parent ec5423d commit 865cd35c9b357e20994f6c6a51f2ae000ba0a3ee @claudep claudep committed May 5, 2012
@@ -22,7 +22,8 @@ def unique_messages():
cmd = 'msguniq "%s.po"' % pf
stdout = os.popen(cmd)
msg = stdout.read()
- open('%s.po' % pf, 'w').write(msg)
+ with open('%s.po' % pf, 'w') as fp:
+ fp.write(msg)
if __name__ == "__main__":
unique_messages()
@@ -120,12 +120,9 @@ def load_spatialite_sql(self):
# Opening up the SpatiaLite SQL initialization file and executing
# as a script.
- sql_fh = open(spatialite_sql, 'r')
- try:
+ with open(spatialite_sql, 'r') as sql_fh:
cur = self.connection._cursor()
cur.executescript(sql_fh.read())
- finally:
- sql_fh.close()
def spatialite_init_file(self):
# SPATIALITE_SQL may be placed in settings to tell GeoDjango
@@ -7,10 +7,10 @@ def fromfile(file_h):
"""
# If given a file name, get a real handle.
if isinstance(file_h, basestring):
- file_h = open(file_h, 'rb')
-
- # Reading in the file's contents,
- buf = file_h.read()
+ with open(file_h, 'rb') as file_h:
+ buf = file_h.read()
+ else:
+ buf = file_h.read()
# If we get WKB need to wrap in buffer(), so run through regexes.
if wkt_regex.match(buf) or hex_regex.match(buf):
@@ -47,18 +47,15 @@ def _key_to_file(self, session_key=None):
def load(self):
session_data = {}
try:
- session_file = open(self._key_to_file(), "rb")
- try:
+ with open(self._key_to_file(), "rb") as session_file:
file_data = session_file.read()
- # Don't fail if there is no data in the session file.
- # We may have opened the empty placeholder file.
- if file_data:
- try:
- session_data = self.decode(file_data)
- except (EOFError, SuspiciousOperation):
- self.create()
- finally:
- session_file.close()
+ # Don't fail if there is no data in the session file.
+ # We may have opened the empty placeholder file.
+ if file_data:
+ try:
+ session_data = self.decode(file_data)
+ except (EOFError, SuspiciousOperation):
+ self.create()
except IOError:
self.create()
return session_data
@@ -31,16 +31,13 @@ def get(self, key, default=None, version=None):
fname = self._key_to_file(key)
try:
- f = open(fname, 'rb')
- try:
+ with open(fname, 'rb') as f:
exp = pickle.load(f)
now = time.time()
if exp < now:
self._delete(fname)
else:
return pickle.load(f)
- finally:
- f.close()
except (IOError, OSError, EOFError, pickle.PickleError):
pass
return default
@@ -61,13 +58,10 @@ def set(self, key, value, timeout=None, version=None):
if not os.path.exists(dirname):
os.makedirs(dirname)
- f = open(fname, 'wb')
- try:
+ with open(fname, 'wb') as f:
now = time.time()
pickle.dump(now + timeout, f, pickle.HIGHEST_PROTOCOL)
pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
- finally:
- f.close()
except (IOError, OSError):
pass
@@ -94,17 +88,14 @@ def has_key(self, key, version=None):
self.validate_key(key)
fname = self._key_to_file(key)
try:
- f = open(fname, 'rb')
- try:
+ with open(fname, 'rb') as f:
exp = pickle.load(f)
- now = time.time()
- if exp < now:
- self._delete(fname)
- return False
- else:
- return True
- finally:
- f.close()
+ now = time.time()
+ if exp < now:
+ self._delete(fname)
+ return False
+ else:
+ return True
except (IOError, OSError, EOFError, pickle.PickleError):
return False
@@ -9,10 +9,9 @@
Example Usage::
>>> from django.core.files import locks
- >>> f = open('./file', 'wb')
- >>> locks.lock(f, locks.LOCK_EX)
- >>> f.write('Django')
- >>> f.close()
+ >>> with open('./file', 'wb') as f:
+ >>> locks.lock(f, locks.LOCK_EX)
+ >>> f.write('Django')
"""
__all__ = ('LOCK_EX','LOCK_SH','LOCK_NB','lock','unlock')
@@ -59,8 +59,7 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove
pass
# first open the old file, so that it won't go away
- old_file = open(old_file_name, 'rb')
- try:
+ with open(old_file_name, 'rb') as old_file:
# now open the new file, not forgetting allow_overwrite
fd = os.open(new_file_name, os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0) |
(not allow_overwrite and os.O_EXCL or 0))
@@ -73,8 +72,6 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove
finally:
locks.unlock(fd)
os.close(fd)
- finally:
- old_file.close()
copystat(old_file_name, new_file_name)
try:
@@ -265,7 +265,8 @@ def attach(self, filename=None, content=None, mimetype=None):
def attach_file(self, path, mimetype=None):
"""Attaches a file from the filesystem."""
filename = os.path.basename(path)
- content = open(path, 'rb').read()
+ with open(path, 'rb') as f:
+ content = f.read()
self.attach(filename, content, mimetype)
def _create_message(self, msg):
@@ -5,8 +5,8 @@
from django.core.management.base import BaseCommand, CommandError
def has_bom(fn):
- f = open(fn, 'r')
- sample = f.read(4)
+ with open(fn, 'r') as f:
+ sample = f.read(4)
return sample[:3] == '\xef\xbb\xbf' or \
sample.startswith(codecs.BOM_UTF16_LE) or \
sample.startswith(codecs.BOM_UTF16_BE)
@@ -112,7 +112,8 @@ def copy_plural_forms(msgs, locale, domain, verbosity, stdout=sys.stdout):
for domain in domains:
django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain)
if os.path.exists(django_po):
- m = plural_forms_re.search(open(django_po, 'rU').read())
+ with open(django_po, 'rU') as fp:
+ m = plural_forms_re.search(fp.read())
if m:
if verbosity > 1:
stdout.write("copying plural forms: %s\n" % m.group('value'))
@@ -141,11 +142,8 @@ def write_pot_file(potfile, msgs, file, work_file, is_templatized):
msgs = '\n'.join(dropwhile(len, msgs.split('\n')))
else:
msgs = msgs.replace('charset=CHARSET', 'charset=UTF-8')
- f = open(potfile, 'ab')
- try:
- f.write(msgs)
- finally:
- f.close()
+ with open(potfile, 'ab') as fp:
+ fp.write(msgs)
def process_file(file, dirpath, potfile, domain, verbosity,
extensions, wrap, location, stdout=sys.stdout):
@@ -164,15 +162,13 @@ def process_file(file, dirpath, potfile, domain, verbosity,
if domain == 'djangojs' and file_ext in extensions:
is_templatized = True
orig_file = os.path.join(dirpath, file)
- src_data = open(orig_file).read()
+ with open(orig_file) as fp:
+ src_data = fp.read()
src_data = prepare_js_for_gettext(src_data)
thefile = '%s.c' % file
work_file = os.path.join(dirpath, thefile)
- f = open(work_file, "w")
- try:
- f.write(src_data)
- finally:
- f.close()
+ with open(work_file, "w") as fp:
+ fp.write(src_data)
cmd = (
'xgettext -d %s -L C %s %s --keyword=gettext_noop '
'--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 '
@@ -184,14 +180,12 @@ def process_file(file, dirpath, potfile, domain, verbosity,
orig_file = os.path.join(dirpath, file)
is_templatized = file_ext in extensions
if is_templatized:
- src_data = open(orig_file, "rU").read()
+ with open(orig_file, "rU") as fp:
+ src_data = fp.read()
thefile = '%s.py' % file
content = templatize(src_data, orig_file[2:])
- f = open(os.path.join(dirpath, thefile), "w")
- try:
- f.write(content)
- finally:
- f.close()
+ with open(os.path.join(dirpath, thefile), "w") as fp:
+ fp.write(content)
work_file = os.path.join(dirpath, thefile)
cmd = (
'xgettext -d %s -L Python %s %s --keyword=gettext_noop '
@@ -232,11 +226,8 @@ def write_po_file(pofile, potfile, domain, locale, verbosity, stdout,
os.unlink(potfile)
raise CommandError("errors happened while running msguniq\n%s" % errors)
if os.path.exists(pofile):
- f = open(potfile, 'w')
- try:
- f.write(msgs)
- finally:
- f.close()
+ with open(potfile, 'w') as fp:
+ fp.write(msgs)
msgs, errors = _popen('msgmerge %s %s -q "%s" "%s"' %
(wrap, location, pofile, potfile))
if errors:
@@ -247,11 +238,8 @@ def write_po_file(pofile, potfile, domain, locale, verbosity, stdout,
msgs = copy_plural_forms(msgs, locale, domain, verbosity, stdout)
msgs = msgs.replace(
"#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % domain, "")
- f = open(pofile, 'wb')
- try:
- f.write(msgs)
- finally:
- f.close()
+ with open(pofile, 'wb') as fp:
+ fp.write(msgs)
os.unlink(potfile)
if no_obsolete:
msgs, errors = _popen('msgattrib %s %s -o "%s" --no-obsolete "%s"' %
@@ -157,13 +157,12 @@ def custom_sql_for_model(model, style, connection):
os.path.join(app_dir, "%s.sql" % opts.object_name.lower())]
for sql_file in sql_files:
if os.path.exists(sql_file):
- fp = open(sql_file, 'U')
- for statement in statements.split(fp.read().decode(settings.FILE_CHARSET)):
- # Remove any comments from the file
- statement = re.sub(ur"--.*([\n\Z]|$)", "", statement)
- if statement.strip():
- output.append(statement + u";")
- fp.close()
+ with open(sql_file, 'U') as fp:
+ for statement in statements.split(fp.read().decode(settings.FILE_CHARSET)):
+ # Remove any comments from the file
+ statement = re.sub(ur"--.*([\n\Z]|$)", "", statement)
+ if statement.strip():
+ output.append(statement + u";")
return output
@@ -176,9 +176,8 @@ def runfastcgi(argset=[], **kwargs):
become_daemon(our_home_dir=options["workdir"], **daemon_kwargs)
if options["pidfile"]:
- fp = open(options["pidfile"], "w")
- fp.write("%d\n" % os.getpid())
- fp.close()
+ with open(options["pidfile"], "w") as fp:
+ fp.write("%d\n" % os.getpid())
WSGIServer(get_internal_wsgi_application(), **wsgi_opts).run()
@@ -328,9 +328,8 @@ def render(self, context):
else:
return '' # Fail silently for invalid includes.
try:
- fp = open(filepath, 'r')
- output = fp.read()
- fp.close()
+ with open(filepath, 'r') as fp:
+ output = fp.read()
except IOError:
output = ''
if self.parsed:
@@ -52,11 +52,8 @@ def get_template_sources(self, template_name, template_dirs=None):
def load_template_source(self, template_name, template_dirs=None):
for filepath in self.get_template_sources(template_name, template_dirs):
try:
- file = open(filepath)
- try:
- return (file.read().decode(settings.FILE_CHARSET), filepath)
- finally:
- file.close()
+ with open(filepath) as fp:
+ return (fp.read().decode(settings.FILE_CHARSET), filepath)
except IOError:
pass
raise TemplateDoesNotExist(template_name)
@@ -34,11 +34,8 @@ def load_template_source(self, template_name, template_dirs=None):
tried = []
for filepath in self.get_template_sources(template_name, template_dirs):
try:
- file = open(filepath)
- try:
- return (file.read().decode(settings.FILE_CHARSET), filepath)
- finally:
- file.close()
+ with open(filepath) as fp:
+ return (fp.read().decode(settings.FILE_CHARSET), filepath)
except IOError:
tried.append(filepath)
if tried:
@@ -226,7 +226,8 @@ def _load_testfile(filename, package, module_relative):
# get_data() opens files as 'rb', so one must do the equivalent
# conversion as universal newlines would do.
return file_contents.replace(os.linesep, '\n'), filename
- return open(filename).read(), filename
+ with open(filename) as fp:
+ return fp.read(), filename
def _indent(s, indent=4):
"""
@@ -2519,9 +2520,8 @@ def debug_script(src, pm=False, globs=None):
# docs say, a file so created cannot be opened by name a second time
# on modern Windows boxes, and execfile() needs to open it.
srcfilename = tempfile.mktemp(".py", "doctestdebug")
- f = open(srcfilename, 'w')
- f.write(src)
- f.close()
+ with open(srcfilename, 'w') as fp:
+ fp.write(src)
try:
if globs:
@@ -15,9 +15,8 @@
... link=u"http://www.holovaty.com/test/",
... description="Testing."
... )
->>> fp = open('test.rss', 'w')
->>> feed.write(fp, 'utf-8')
->>> fp.close()
+>>> with open('test.rss', 'w') as fp:
+>>> feed.write(fp, 'utf-8')
For definitions of the different versions of RSS, see:
http://diveintomark.org/archives/2004/02/04/incompatible-rss
@@ -333,11 +333,8 @@ def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, mod
source = source.splitlines()
if source is None:
try:
- f = open(filename)
- try:
- source = f.readlines()
- finally:
- f.close()
+ with open(filename) as fp:
+ source = fp.readlines()
except (OSError, IOError):
pass
if source is None:
Oops, something went wrong.

0 comments on commit 865cd35

Please sign in to comment.