cta-observatory / pyeventio

Python read-only implementation for the EventIO data format used by the CORSIKA 7 IACT extension and sim_telarray
MIT License
10 stars 12 forks source link

Fix exception when closing non-eventio files #282

Closed vmharvey closed 4 weeks ago

vmharvey commented 4 weeks ago

If a non-eventio file is opened (either a file not in the expected formats, or an empty file such as caused by a failed run of sim_telarray), an exception is raised if close() is called on the EventIOFile object. This happens automatically if the variable goes out of scope, such as in the common operation of a loop over input files.

Example

# File: test.py

import sys
from eventio import EventIOFile

for _ in range(1):
  try:
    file = EventIOFile(sys.argv[1])
  except Exception as ex:
    print("Error:", ex)
    continue

  ## processing would go here ##
$ python test.py /dev/random

Output:

Error: File /dev/random is not an eventio file
Exception ignored in: <function EventIOFile.__del__ at 0x7fcfb01ce2a0>
Traceback (most recent call last):
  File "<snip>/lib/python3.12/site-packages/eventio/base.py", line 156, in __del__
    self.close()
  File "<snip>/lib/python3.12/site-packages/eventio/base.py", line 153, in close
    self._filehandle.close()
    ^^^^^^^^^^^^^^^^
AttributeError: 'EventIOFile' object has no attribute '_filehandle'

Fortunately in this case, the exception isn't considered fatal. But it is still noisy and can be fixed by checking the status of _filehandle before operating on it.

Other notes

Incidentally, in the case of empty files, instead an opaque IndexError is raised by the method that attempts to read the file and discern its type. You can see this if you try /dev/null instead of /dev/random with this test script. But the follow-on issues are the same.

maxnoe commented 4 weeks ago

Thanks a lot @vmharvey

maxnoe commented 4 weeks ago

I'll also make a fix for the other issue, or do you already have a solution?

vmharvey commented 4 weeks ago

I'll also make a fix for the other issue, or do you already have a solution?

All good! I was considering preparing a fix, but didn't have one ready to go. Perfectly happy to see that you got to it first :D