46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
import os
|
|
import nixio as nix
|
|
from nixio import file
|
|
|
|
class Singleton(type):
|
|
_instances = {}
|
|
def __call__(cls, *args, **kwargs):
|
|
if cls not in cls._instances:
|
|
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
|
return cls._instances[cls]
|
|
|
|
class FileHandler(metaclass=Singleton):
|
|
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
self._nix_file = None
|
|
self._file_requests = []
|
|
|
|
def open(self, filename):
|
|
"""[summary]
|
|
|
|
Args:
|
|
filename ([type]): [description]
|
|
"""
|
|
self.close()
|
|
|
|
if not os.path.exists(filename):
|
|
return False, "File %s could not be found!" % filename
|
|
try:
|
|
self._nix_file = nix.File.open(filename, nix.FileMode.ReadOnly)
|
|
return True, "Successfully opened file %s." % filename.split(os.sep)[-1]
|
|
except RuntimeError as e:
|
|
return False, "Failed to open file %s! \n Error message is: %s" % (filename, e)
|
|
except OSError as e:
|
|
return False, "Failed to open file %s! \n Error message is: %s\n Probably no nix file?!" % (filename, e)
|
|
|
|
def close(self):
|
|
# TODO check if there are any pending file requests!
|
|
if self._nix_file is not None and self._nix_file.is_open():
|
|
self._nix_file.close()
|
|
self._nix_file = None
|
|
self._file_requests = []
|
|
|
|
@property
|
|
def is_valid(self):
|
|
return self._nix_file is not None and self._nix_file.is_open() |