Issue
The Qt4.8 documentation (as mentioned here) suggests that a QtCore.QFile-object closes its file upon destruction (if the file is open).
Does that mean that this PyQt4 snippet
my_file = QtCore.QFile('some_file.bin')
my_file.open(QtCore.QFile.ReadOnly)
... do stuff that might raise an exception ...
is similar to this non-PyQt snippet, which uses open()
as context manager?
with open('some_file.bin', 'rb') as my_file:
... do stuff that might raise an exception ...
That is, in terms of the file being closed automatically when something goes wrong and the program exits (as discussed e.g. here).
Solution
No. A QFile
will not be closed automatically if an error occurs. And in fact, there will be no exception raised either. Qt just doesn't do exceptions at all, so you will need to check return values and query the error()
method instead.
Here's some example output:
>>> f = QtCore.QFile('/tmp/test.txt')
>>> f.open(QtCore.QIODevice.ReadWrite)
True
>>> f.resize(10)
True
Note how Qt just returns True/False
here, whereas Python would raise an OSError/IOError
if a problem had occurred.
>>> f.readAll()
PyQt4.QtCore.QByteArray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> f.error() == QtCore.QFile.NoError
True
An explicit check was required here to make sure no error occured when reading.
>>> f.close()
>>> f.open(QtCore.QIODevice.ReadOnly)
True
>>> f.resize(20)
False
>>> f.error() == QtCore.QFile.ResizeError
True
So now an error as been induced - but no exception is raised, and the file is still open and readable:
>>> f.isOpen()
True
>>> f.readAll()
PyQt4.QtCore.QByteArray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> f.error() == QtCore.QFile.NoError
True
Deleting a QFile
will automatically close it; but otherwise, you will need to explicitly close it to free up resources - even if errors occurred during its lifetime.
Answered By - ekhumoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.