Skip to content
This repository has been archived by the owner on Mar 4, 2021. It is now read-only.

Commit

Permalink
Merge pull request #28 from cta-sst-1m/issue_25
Browse files Browse the repository at this point in the history
try to fix issue 25 by ensuring resources are correctly closed
  • Loading branch information
Dominik Neise authored May 11, 2018
2 parents 1a14f82 + bd3221a commit b1847d2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

## Usage example:

**Note**: At the moment multiple open files at the same time are not supported.


If you are just starting with proto-z-fits files and would like to explore the file contents, try this:
Expand Down
35 changes: 30 additions & 5 deletions protozfits/simple.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from enum import Enum
from collections import namedtuple
from warnings import warn
import numpy as np
from astropy.io import fits

Expand Down Expand Up @@ -30,7 +31,17 @@ def get_class_from_PBFHEAD(pbfhead):


class File:
instances = 0

def __init__(self, path, pure_protobuf=False):
File.instances += 1
if File.instances > 1:
warn('''\
Multiple open zfits files at the same time are not supported.
Reading from mutliple open tables at the same time will reset these
tables continously and you will read always the same events.
''')
Table._Table__last_opened = None
bintable_descriptions = detect_bintables(path)
for btd in bintable_descriptions:
self.__dict__[btd.extname] = Table(btd, pure_protobuf)
Expand All @@ -41,6 +52,18 @@ def __repr__(self):
self.__dict__
)

def __enter__(self):
return self

def __exit__(self, type, value, tb):
self.close()

def close(self):
File.instances -= 1

def __del__(self):
self.close()


BinTableDescription = namedtuple(
'BinTableDescription',
Expand Down Expand Up @@ -98,7 +121,6 @@ def __len__(self):
return self.__desc.znaxis2

def __iter__(self):
rewind_table()
return self

def __next__(self):
Expand All @@ -108,13 +130,14 @@ def __next__(self):
row = self.__pbuf_class()
try:
row.ParseFromString(rawzfitsreader.readEvent())
if not self.pure_protobuf:
return make_namedtuple(row)
else:
return row
except EOFError:
raise StopIteration

if not self.pure_protobuf:
return make_namedtuple(row)
else:
return row

def __repr__(self):
return '{cn}({d.znaxis2}x{d.pbfhead})'.format(
cn=self.__class__.__name__,
Expand Down Expand Up @@ -149,6 +172,7 @@ def message_getitem(msg, name):
messages.add(thing)



def namedtuple_repr2(self):
'''a nicer repr for big namedtuples containing big numpy arrays'''
old_print_options = np.get_printoptions()
Expand Down Expand Up @@ -179,6 +203,7 @@ def nt(m):
_nt.__repr__ = namedtuple_repr2
return _nt


named_tuples = {m: nt(m) for m in messages}

enum_types = {}
Expand Down

0 comments on commit b1847d2

Please sign in to comment.