File: nmea_file.py

package info (click to toggle)
python-nmea2 1.19.0-3
  • links: PTS
  • area: main
  • in suites: sid, trixie
  • size: 420 kB
  • sloc: python: 2,948; makefile: 3
file content (80 lines) | stat: -rw-r--r-- 2,014 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
try:
    # pylint: disable=used-before-assignment
    basestring = basestring
except NameError: # py3
    basestring = str

from .nmea import NMEASentence


class NMEAFile(object):
    """
    Reads NMEA sentences from a file similar to a standard python file object.
    """

    def __init__(self, f, *args, **kwargs):
        super(NMEAFile, self).__init__()
        if isinstance(f, basestring) or args or kwargs:
            self._file = self.open(f, *args, **kwargs)
        else:
            self._file = f
        self._context = None

    def open(self, fp, mode='r'):
        """
        Open the NMEAFile.
        """
        self._file = open(fp, mode=mode)
        return self._file

    def close(self):
        """
        Close the NMEAFile.
        """
        self._file.close()

    def __iter__(self):
        """
        Iterate through the file yielding NMEASentences
        :return:
        """
        for line in self._file:
            yield self.parse(line)

    def __enter__(self):
        if hasattr(self._file, '__enter__'):
            self._context = self._file.__enter__()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self._context:
            ctx = self._context
            self._context = None
            ctx.__exit__(exc_type, exc_val, exc_tb)

    def next(self):
        """
        Iterate through the file object returning NMEASentence objects
        :return: NMEASentence
        """
        data = self._file.readline()
        return self.parse(data)

    def parse(self, s):
        return NMEASentence.parse(s)

    def readline(self):
        """
        Return the next NMEASentence in the file object
        :return: NMEASentence
        """
        data = self._file.readline()
        s = self.parse(data)
        return s

    def read(self):
        """
        Return a list of NMEASentence objects for each line in the file
        :return: list of NMEASentence objects
        """
        return [s for s in self]