J
J
I have this function in a class:
def write_file(self, data, dest):
with open(dest, 'wb', 0) as outfile:
try:
print("IN WRITE_FILE")
outfile.write(self.data)
except IOError as exc:
logging.error("Unable to write data to %s: %s", dest, exc)
return False
else:
outfile.flush()
os.fsync(outfile.fileno())
return True
Which is simply called like this:
test.write_file(test.data, target_file)
However, when this is called on a read-only filesystem, it throws an OSError:
File "./scripts/removable_storage_test", line 118, in write_file
with open(dest, 'wb', 0) as outfile:
OSError: [Errno 30] Read-only file system:
'/media/bladernr/5747-AD2E/tmpfbzsxk.0'
So what I am not sure of is how to handle this?
Would it be better to wrap the call and catch the OSError there, or
wrap the whole with open() block in the function itself?
My thought is to wrap the with open() call in the function so that I'm
not wrapping the function call every time I use the class somewhere,
but then I am not sure of that as it leads to nested try blocks like
so:
try:
with open(dest, 'wb', 0) as outfile:
try:
stuff
except IOError as exec:
more stuff
else:
other stuff
except OSError as exc:
error handling stuff
return False
I think, functionally, that should work, but should nested try/except
blocks be avoided?
def write_file(self, data, dest):
with open(dest, 'wb', 0) as outfile:
try:
print("IN WRITE_FILE")
outfile.write(self.data)
except IOError as exc:
logging.error("Unable to write data to %s: %s", dest, exc)
return False
else:
outfile.flush()
os.fsync(outfile.fileno())
return True
Which is simply called like this:
test.write_file(test.data, target_file)
However, when this is called on a read-only filesystem, it throws an OSError:
File "./scripts/removable_storage_test", line 118, in write_file
with open(dest, 'wb', 0) as outfile:
OSError: [Errno 30] Read-only file system:
'/media/bladernr/5747-AD2E/tmpfbzsxk.0'
So what I am not sure of is how to handle this?
Would it be better to wrap the call and catch the OSError there, or
wrap the whole with open() block in the function itself?
My thought is to wrap the with open() call in the function so that I'm
not wrapping the function call every time I use the class somewhere,
but then I am not sure of that as it leads to nested try blocks like
so:
try:
with open(dest, 'wb', 0) as outfile:
try:
stuff
except IOError as exec:
more stuff
else:
other stuff
except OSError as exc:
error handling stuff
return False
I think, functionally, that should work, but should nested try/except
blocks be avoided?