file_parser.py 4.62 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Copyright 2018 Markus Scheidgen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an"AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import os
import logging
import pint
from typing import Any, Dict
20
21
22
import gzip
import bz2
import lzma
23
import tarfile
24
25
26
27


class FileParser:
    '''
28
    Base class for parsers. The parse method specific to a file type
29
    should be implemented in the corresponding child class. The parsed quantities are
30
    stored in results. One can access a quantity by using the get method or as attribute.
31
32
33
34
35

    Arguments:
        mainfile: the file to be parsed
        logger: optional logger
    '''
36
37
38
39
40
41
42
43
44
45
46
    def __init__(self, mainfile=None, logger=None, open=None):
        self._mainfile: Any = None
        self._mainfile_obj: Any = None
        if isinstance(mainfile, str):
            self._mainfile = os.path.abspath(mainfile)
            self._mainfile_obj = None
        elif hasattr(mainfile, 'name'):
            self._mainfile = mainfile.name
            self._mainfile_obj = mainfile
        self._open = open
        self.logger = logger if logger is not None else logging
47
48
49
50
51
52
        self._results: Dict[str, Any] = None
        # a key is necessary for xml parsers, where parsing is done dynamically
        self._key: str = None
        self._kwargs: Dict[str, Any] = None
        self._file_handler: Any = None

53
54
55
    def init_parameters(self):
        pass

56
57
58
59
60
61
62
63
64
65
66
67
68
    @property
    def results(self):
        if self._results is None:
            self._results = dict()
        if self._key not in self._results:
            self.parse(self._key, **self._kwargs)

        return self._results

    @property
    def maindir(self):
        return os.path.dirname(self._mainfile)

69
70
71
72
73
74
75
76
77
78
    @property
    def mainfile_obj(self):
        if self._mainfile_obj is None:
            try:
                self._mainfile_obj = self.open(self._mainfile)
            except Exception:
                pass

        return self._mainfile_obj

79
80
81
82
83
    @property
    def mainfile(self):
        if self._mainfile is None:
            return

84
        if self._mainfile_obj is None and not os.path.isfile(self._mainfile):
85
86
87
88
89
90
91
            return
        return self._mainfile

    @mainfile.setter
    def mainfile(self, val):
        self._results = None
        self._file_handler = None
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
        self._mainfile = None
        if isinstance(val, str):
            self._mainfile = os.path.abspath(val)
            self._mainfile_obj = None
        elif hasattr(val, 'name'):
            self._mainfile = val.name
            self._mainfile_obj = val
        self.init_parameters()

    def open(self, mainfile):
        open_file = self._open
        if open_file is None:
            if mainfile.endswith('.gz'):
                open_file = gzip.open
            elif mainfile.endswith('.bz2'):
                open_file = bz2.open
            elif mainfile.endswith('.xz'):
                open_file = lzma.open
            elif mainfile.endswith('.tar'):
                open_file = tarfile.open
            else:
                open_file = open
        return open_file(mainfile)
115

116
117
118
119
120
121
    def get(self, key: str, default: Any = None, unit: str = None, **kwargs):
        '''
        Returns the parsed result for quantity with name key. If quantity is not in
        results default will be returned. A pint unit can be provided which is attached
        to the returned value.
        '''
Alvin Noe Ladines's avatar
Alvin Noe Ladines committed
122
123
124
        if self.mainfile is None:
            return default

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        self._key = key
        self._kwargs = kwargs
        val = self.results.get(key, None)
        if val is None:
            val = default

        if val is None:
            return

        if unit is not None:
            if isinstance(unit, pint.Quantity):
                val = val * unit

            elif isinstance(val, pint.Quantity):
                val = val.to(unit)

            else:
                val = pint.Quantity(val, unit)

        return val

    def __getitem__(self, key):
        if isinstance(key, str):
            return self.get(key)
        elif isinstance(key, int):
            return self[int]

152
153
154
155
156
157
158
    def __getattr__(self, key):
        if key not in self._results:
            self.parse(key)
        return self._results.get(key)

    def parse(self, quantity_key: str = None, **kwargs):
        pass