from . import Driver as Driver
+class Closing (object):
+ """Add .__enter__() .__exit__() for `with` statements.
+
+ See :pep:`343`.
+ """
+ def __init__(self, obj):
+ self.obj = obj
+
+ def __enter__(self):
+ return self.obj
+
+ def __exit__(self, *exc_info):
+ try:
+ close_it = self.obj.close
+ except AttributeError:
+ pass
+ else:
+ close_it()
+
+
class JPKDriver (Driver):
"""Handle JPK ForceRobot's data format.
"""
def is_me(self, path):
if zipfile.is_zipfile(path): # JPK file versions since at least 0.5
- f = h = None
- try:
- f = zipfile.ZipFile(path, 'r')
+ with Closing(zipfile.ZipFile(path, 'r')) as f:
if 'header.properties' not in f.namelist():
return False
- h = f.open('header.properties')
- if 'jpk-data-file' in h.read():
- return True
- finally:
- if h != None:
- h.close()
- if f != None:
- f.close()
+ with Closing(f.open('header.properties')) as h:
+ if 'jpk-data-file' in h.read():
+ return True
else:
- f = None
- try:
- f = open(path, 'r')
+ with Closing(open(path, 'r')) as f:
headlines = []
for i in range(3):
headlines.append(f.readline())
if headlines[0].startswith('# xPosition') \
and headlines[1].startswith('# yPosition'):
return True
- finally:
- if f != None:
- f.close()
return False
def read(self, path):
return self._read_old(path)
def _read_zip(self, path):
- f = None
- try:
- f = zipfile.ZipFile(path, 'r')
+ with Closing(zipfile.ZipFile(path, 'r')) as f:
f.path = path
info = self._zip_info(f)
approach = self._zip_segment(f, info, 0)
assert retract.info['name'] == 'retract', retract.info['name']
return ([approach, retract],
self._zip_translate_params(info, retract.info['raw info']))
- finally:
- if f != None:
- f.close()
def _zip_info(self, zipfile):
- h = None
- try:
- h = zipfile.open('header.properties')
- info = self._parse_params(h.readlines())
+ with Closing(zipfile.open('header.properties')) as f:
+ info = self._parse_params(f.readlines())
return info
- finally:
- if h != None:
- h.close()
def _zip_segment(self, zipfile, info, index):
prop_file = zipfile.open(os.path.join(