Commit 45467588 authored by Daniel Armbruster's avatar Daniel Armbruster Committed by thomas.forbriger
Browse files

use with statment to guarantee closing the file descriptors

This is a legacy commit from before 2015-05-18.
It may be incomplete as well as inconsistent.
See COPYING.legacy and README.history for details.


SVN Path:     http://gpitrsvn.gpi.uni-karlsruhe.de/repos/TFSoftware/trunk
SVN Revision: 5056
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent fde337e9
......@@ -44,6 +44,7 @@
# 26/02/2013 V0.6 introduce csbackErrorCodes; provide a simplified
# CsLine.check() function (provide no logging anymore)
# 12/03/2013 V0.6.1 BUG in CsFile.check() function fixed
# 14/03/2013 V0.6.2 make use with statement
#
# =============================================================================
""" CsFile module to handle checksumfiles. """
......@@ -61,7 +62,7 @@ from datetime import date
import csbacklog
import csbackErrorCodes as eCodes
__version__ = "V0.6"
__version__ = "V0.6.2"
__subversion__ = "$Id$"
__license__ = "GPLv2+"
__author__ = "Daniel Armbruster"
......@@ -177,14 +178,13 @@ class CsFile:
else:
try:
self.logger.debug("Start reading checksumfile '%s'",path)
csfile = open(path)
self.__cslines = [CsLine(line.split(), self.srcdir) \
for line in csfile if len(line.rstrip()) and line[0] != '#']
with open(path, 'r') as csfile:
self.__cslines = [CsLine(line.split(), self.srcdir) \
for line in csfile if len(line.rstrip()) and line[0] != '#']
except IOError as err:
raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
+err.filename, eCodes.CSFILE_UnableToReadChecksumFile)
else:
csfile.close()
self.logger.debug("Finished reading checksumfile '%s'", path)
def append(self, cslines):
......@@ -197,20 +197,19 @@ class CsFile:
else:
try:
self.logger.debug("Start appending to checksumfile '%s'", path)
csfile = open(path, 'a')
for csline in cslines:
self.logger.debug("Writing line '%s'", str(csline))
if isinstance(csline, CsLine):
csfile.write(str(csline) + '\n')
else:
raise CsFileError("Argument must be of type CsLine.", \
eCodes.CSFILE_InvalidDataType)
with open(path, 'a') as csfile:
for csline in cslines:
self.logger.debug("Writing line '%s'", str(csline))
if isinstance(csline, CsLine):
csfile.write(str(csline) + '\n')
else:
raise CsFileError("Argument must be of type CsLine.", \
eCodes.CSFILE_InvalidDataType)
except IOError as err:
raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
+err.filename, eCodes.CSFILE_UnableToAppend)
+err.filename, eCodes.CSFILE_UnableToAppend)
else:
self.logger.debug("Finished appending to checksumfile '%s'", path)
csfile.close()
def update(self, regexes=[]):
"""
......@@ -442,17 +441,15 @@ class CsLine:
try:
hashfunc = hashlib.new(self.hashfunc)
blockSize = chunkSize * hashfunc.block_size
file = open(path, 'rb')
data = file.read(blockSize)
while data:
hashfunc.update(data)
with open(path, 'rb') as file:
data = file.read(blockSize)
self.checksum = hashfunc.hexdigest()
while data:
hashfunc.update(data)
data = file.read(blockSize)
self.checksum = hashfunc.hexdigest()
except IOError as err:
raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
+err.filename, eCodes.CSFILE_UnableToReadDataFile)
else:
file.close()
# set remaining data
self.creationDateFile = \
......@@ -474,19 +471,18 @@ class CsLine:
blockSize = chunkSize * hashfunc.block_size
path = os.path.join(self.srcdir, self.filename)
try:
file = open(path, 'rb')
with open(path, 'rb') as file:
# calculate checksum
data = file.read(blockSize)
while data:
hashfunc.update(data)
data = file.read(blockSize)
checksum = hashfunc.hexdigest()
except IOError:
raise CsFileError("While checking: file '{0}' does not exist.".format( \
path), eCodes.CSFILE_DataFileNotExistent)
else:
# calculate checksum
data = file.read(blockSize)
while data:
hashfunc.update(data)
data = file.read(blockSize)
checksum = hashfunc.hexdigest()
file.close()
return checksum == self.checksum
return checksum == self.checksum
def __str__(self):
"""
......
......@@ -130,14 +130,11 @@ class Lock:
if DEBUG:
sys.stdout.write( \
"DEBUG: Creating lock of directory '{0}' ...\n".format(self.dir))
pidfile = open(self.path, 'w')
pidfile.write("{0}".format(self.pid))
with open(self.path, 'w') as pidfile:
pidfile.write("{0}".format(self.pid))
except IOError as err:
raise LockError("While creating lockfile. "+err.strerror+" [Errno "+ \
str(err.errno)+"]: "+err.filename, eCodes.LOCK_UnableToCreate)
else:
pidfile.close()
def release(self, pid):
......@@ -154,23 +151,22 @@ class Lock:
"DEBUG: Releasing lock of directory '{0}'.\n".format(self.dir))
try:
pidfile = open(self.path, 'r')
pidfile.seek(0)
with open(self.path, 'r') as pidfile:
pidfile.seek(0)
if pidfile.readline() == str(pid):
try:
pidfile.close()
os.remove(self.path)
# remove PID from registration list
if pid in Lock.activeLockPids:
Lock.activeLockPids.remove(pid)
except:
raise LockError("Unable to remove lock", eCodes.LOCK_UnableToRemove)
else:
raise LockError("Invalid PID passed", eCodes.LOCK_InvalidPID)
except:
raise LockError("Missing lock file in directory '{0}'".format( \
self.dir), eCodes.LOCK_LockFileMissing)
else:
if pidfile.readline() == str(pid):
try:
pidfile.close()
os.remove(self.path)
# remove PID from registration list
if pid in Lock.activeLockPids:
Lock.activeLockPids.remove(pid)
except:
raise LockError("Unable to remove lock", eCodes.LOCK_UnableToRemove)
else:
raise LockError("Invalid PID passed", eCodes.LOCK_InvalidPID)
def __lockValid(self):
......@@ -178,10 +174,9 @@ class Lock:
Check if the process with the pid in the pid lockfile is still active.
"""
try:
pidfile = open(self.path, 'r')
pidfile.seek(0)
pid = pidfile.readline().strip()
pidfile.close()
with open(self.path, 'r') as pidfile:
pidfile.seek(0)
pid = pidfile.readline().strip()
if 0 == len(pid):
return False
if DEBUG:
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment